Queries to find the minimum index in given array having at least value X | JavaScript program for above approach ; Function to find the smallest index of an array element whose value is less than or equal to Q [ i ] ; Stores size of array ; Stores coun of queries ; Store array elements along with the index ; Store smallest index of an array element whose value is greater than or equal to i ; Traverse the array ; Insert { arr [ i ] , i } into storeArrIdx [ ] ; Sort the array ; Sort the storeArrIdx ; Stores index of arr [ N - 1 ] in sorted order ; Traverse the array storeArrIdx [ ] ; Update minIdx [ i ] ; Traverse the array Q [ ] ; Store the index of lower_bound of Q [ i ] ; If no index found whose value greater than or equal to arr [ i ] ; Print smallest index whose value greater than or equal to Q [ i ] ; Driver function
class pair { constructor ( element , index ) { this . element = element ; this . index = index ; } } function minimumIndex ( arr , Q ) { let N = arr . length ; let M = Q . length ; let storeArrIdx = [ ] ; let minIdx = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { minIdx [ i ] = 0 ; } for ( let i = 0 ; i < N ; ++ i ) { storeArrIdx . push ( [ arr [ i ] , i ] ) ; } ( arr ) . sort ( function ( a , b ) { return a - b ; } ) ; storeArrIdx . sort ( function ( a , b ) { return a [ 0 ] - b [ 0 ] } ) ; minIdx [ N - 1 ] = storeArrIdx [ N - 1 ] [ 1 ] ; for ( let i = N - 2 ; i >= 0 ; i -- ) { minIdx [ i ] = Math . min ( minIdx [ i + 1 ] , storeArrIdx [ i ] [ 1 ] ) ; } for ( let i = 0 ; i < M ; i ++ ) { let pos = lower_bound ( arr , Q [ i ] ) ; if ( pos == N ) { document . write ( " " + " " ) ; continue ; } document . write ( minIdx [ pos ] + " " ) ; } } function lower_bound ( arr , element ) { for ( let i = 0 ; i < arr . length ; i ++ ) if ( element <= arr [ i ] ) return i ; return arr . length ; } let arr = [ 1 , 9 ] ; let Q = [ 7 , 10 , 0 ] ; minimumIndex ( arr , Q ) ;