Kth smallest element from an array of intervals | 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 ; Remove minimum element ; Check if the minimum of the current interval is less than the maximum of the current interval ; Insert new interval ; Intervals given ; Size of the arr
function KthSmallestNum ( arr , n , k ) { var pq = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { pq . push ( [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ) ; } var cnt = 1 ; while ( cnt < k ) { pq . sort ( ( a , b ) => { if ( a [ 0 ] == b [ 0 ] ) return a [ 1 ] - b [ 1 ] return a [ 0 ] - b [ 0 ] } ) ; var interval = pq [ 0 ] ; pq . shift ( ) ; if ( interval [ 0 ] < interval [ 1 ] ) { pq . push ( [ interval [ 0 ] + 1 , interval [ 1 ] ] ) ; } cnt += 1 ; } pq . sort ( ( a , b ) => { if ( a [ 0 ] == b [ 0 ] ) return a [ 1 ] - b [ 1 ] return a [ 0 ] - b [ 0 ] } ) ; return ( pq [ 0 ] ) [ 0 ] ; } var arr = [ [ 5 , 11 ] , [ 10 , 15 ] , [ 12 , 20 ] ] ; var n = arr . length ; var k = 12 ; document . write ( KthSmallestNum ( arr , n , k ) ) ;