Queries to find the minimum index in given array having at least value X | Python3 program to implement the above approachf ; 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 ] ; Prsmallest index whose value greater than or equal to Q [ i ] ; Driver Code
from bisect import bisect_left NEW_LINE def minimumIndex ( arr , Q ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE M = len ( Q ) NEW_LINE storeArrIdx = [ ] NEW_LINE minIdx = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT storeArrIdx . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE storeArrIdx = sorted ( storeArrIdx ) NEW_LINE minIdx [ N - 1 ] = storeArrIdx [ N - 1 ] [ 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT minIdx [ i ] = min ( minIdx [ i + 1 ] , storeArrIdx [ i ] [ 1 ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT pos = bisect_left ( arr , Q [ i ] ) NEW_LINE if ( pos == N ) : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE continue NEW_LINE DEDENT print ( minIdx [ pos ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 9 ] NEW_LINE Q = [ 7 , 10 , 0 ] NEW_LINE minimumIndex ( arr , Q ) NEW_LINE DEDENT