Kth smallest element from an array of intervals | Java program to implement the above approach ; Function to get the Kth smallest element from an array of intervals ; Store all the intervals so that it returns the minimum element in O ( 1 ) ; Insert all Intervals into the MinHeap ; Stores the count of popped elements ; Iterate over MinHeap ; Stores minimum element from all remaining intervals ; Check if the minimum of the current interval is less than the maximum of the current interval ; Insert new interval ; Driver Code ; Intervals given ; Size of the arr
import java . util . * ; import java . io . * ; class GFG { public static int KthSmallestNum ( int arr [ ] [ ] , int n , int k ) { PriorityQueue < int [ ] > pq = new PriorityQueue < > ( ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; for ( int i = 0 ; i < n ; i ++ ) { pq . add ( new int [ ] { arr [ i ] [ 0 ] , arr [ i ] [ 1 ] } ) ; } int cnt = 1 ; while ( cnt < k ) { int [ ] interval = pq . poll ( ) ; if ( interval [ 0 ] < interval [ 1 ] ) { pq . add ( new int [ ] { interval [ 0 ] + 1 , interval [ 1 ] } ) ; } cnt ++ ; } return pq . peek ( ) [ 0 ] ; } public static void main ( String args [ ] ) { int arr [ ] [ ] = { { 5 , 11 } , { 10 , 15 } , { 12 , 20 } } ; int n = arr . length ; int k = 12 ; System . out . println ( KthSmallestNum ( arr , n , k ) ) ; } }