Queries to find the minimum index in given array having at least value X | Java 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
import java . util . * ; import java . lang . * ; class pair { int element , index ; pair ( int element , int index ) { this . element = element ; this . index = index ; } } class GFG { static void minimumIndex ( int [ ] arr , int [ ] Q ) { int N = arr . length ; int M = Q . length ; ArrayList < pair > storeArrIdx = new ArrayList < > ( ) ; int [ ] minIdx = new int [ N ] ; for ( int i = 0 ; i < N ; ++ i ) { storeArrIdx . add ( new pair ( arr [ i ] , i ) ) ; } Arrays . sort ( arr ) ; Collections . sort ( storeArrIdx , ( a , b ) -> a . element - b . element ) ; minIdx [ N - 1 ] = storeArrIdx . get ( N - 1 ) . index ; for ( int i = N - 2 ; i >= 0 ; i -- ) { minIdx [ i ] = Math . min ( minIdx [ i + 1 ] , storeArrIdx . get ( i ) . index ) ; } for ( int i = 0 ; i < M ; i ++ ) { int pos = lower_bound ( arr , Q [ i ] ) ; if ( pos == N ) { System . out . print ( " - 1" + " ▁ " ) ; continue ; } System . out . print ( minIdx [ pos ] + " ▁ " ) ; } } static int lower_bound ( int [ ] arr , int element ) { for ( int i = 0 ; i < arr . length ; i ++ ) if ( element <= arr [ i ] ) return i ; return arr . length ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 9 } ; int [ ] Q = { 7 , 10 , 0 } ; minimumIndex ( arr , Q ) ; } }