Find the kth element in the series generated by the given N ranges | Function to return the kth element of the required series ; To store the number of integers that lie upto the ith index ; Compute the number of integers ; Stores the index , lying from 1 to n , ; Using binary search , find the index in which the kth element will lie ; Find the position of the kth element in the interval in which it lies ; Driver code
function getKthElement ( n , k , L , R ) { let l = 1 ; let h = n ; let total = new Array ( n + 1 ) ; total [ 0 ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) { total [ i + 1 ] = total [ i ] + ( R [ i ] - L [ i ] ) + 1 ; } let index = - 1 ; while ( l <= h ) { let m = Math . floor ( ( l + h ) / 2 ) ; if ( total [ m ] > k ) { index = m ; h = m - 1 ; } else if ( total [ m ] < k ) l = m + 1 ; else { index = m ; break ; } } l = L [ index - 1 ] ; h = R [ index - 1 ] ; let x = k - total [ index - 1 ] ; while ( l <= h ) { let m = Math . floor ( ( l + h ) / 2 ) ; if ( ( m - L [ index - 1 ] ) + 1 == x ) { return m ; } else if ( ( m - L [ index - 1 ] ) + 1 > x ) h = m - 1 ; else l = m + 1 ; } return k ; } let L = [ 1 , 8 , 21 ] ; let R = [ 4 , 10 , 23 ] ; let n = L . length ; let k = 6 ; document . write ( getKthElement ( n , k , L , R ) ) ;