Smallest index in given range of indices which is not equal to X | Precompute the index of next different element in the array for every array element ; Default value ; Compute nextpos [ i ] using nextpos [ i + 1 ] ; Function to return the smallest index ; nextpos [ i ] will store the next position p where arr [ p ] != arr [ i ] ; If X is not present at l ; Otherwise ; Find the index which stores a value different from X ; If that index is within the range ; Driver code
def precompute ( nextpos , arr , N ) : NEW_LINE INDENT nextpos [ N - 1 ] = N NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] == arr [ i + 1 ] : NEW_LINE INDENT nextpos [ i ] = nextpos [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT nextpos [ i ] = i + 1 NEW_LINE DEDENT DEDENT DEDENT def findIndex ( query , arr , N , Q ) : NEW_LINE INDENT nextpos = [ 0 ] * N NEW_LINE precompute ( nextpos , arr , N ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT l = query [ i ] [ 0 ] NEW_LINE r = query [ i ] [ 1 ] NEW_LINE x = query [ i ] [ 2 ] NEW_LINE ans = - 1 NEW_LINE if arr [ l ] != x : NEW_LINE INDENT ans = l NEW_LINE DEDENT else : NEW_LINE INDENT d = nextpos [ l ] NEW_LINE if d <= r : NEW_LINE INDENT ans = d NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT DEDENT N = 6 NEW_LINE Q = 3 NEW_LINE arr = [ 1 , 2 , 1 , 1 , 3 , 5 ] NEW_LINE query = [ [ 0 , 3 , 1 ] , [ 1 , 5 , 2 ] , [ 2 , 3 , 1 ] ] NEW_LINE findIndex ( query , arr , N , Q ) NEW_LINE