Find the Kth smallest element in the sorted generated array | Function to return the Kth element in B [ ] ; Initialize the count Array ; Reduce N repeatedly to half its value ; Add count to start ; Subtract same count after end index ; Store each element of Array [ ] with their count ; Sort the elements wrt value ; If Kth element is in range of element [ i ] return element [ i ] ; If K is out of bound ; Driver code
function solve ( arr , N , K ) { let count_Arr = new Array ( N + 1 ) . fill ( 0 ) ; let factor = 1 ; let size = N ; while ( size ) { let start = 1 ; let end = size ; count_Arr [ 1 ] += factor * N ; count_Arr [ end + 1 ] -= factor * N ; factor ++ ; size = Math . floor ( size / 2 ) ; } for ( let i = 2 ; i <= N ; i ++ ) count_Arr [ i ] += count_Arr [ i - 1 ] ; let element = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { element . push ( [ arr [ i ] , count_Arr [ i + 1 ] ] ) ; } element . sort ( ( a , b ) => a - b ) ; let start = 1 ; for ( let i = 0 ; i < N ; i ++ ) { let end = start + element [ i ] [ 1 ] - 1 ; if ( K >= start && K <= end ) { return element [ i ] [ 0 ] ; } start += element [ i ] [ 1 ] ; } return - 1 ; } let arr = [ 2 , 4 , 5 , 1 ] ; let N = arr . length ; let K = 13 ; document . write ( solve ( arr , N , K ) ) ;