Smallest index in given range of indices which is not equal to X | Java program to find the smallest index in the array in the range [ L , R ] which does not contain 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
class GFG { static void precompute ( int nextpos [ ] , int arr [ ] , int N ) { nextpos [ N - 1 ] = N ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] == arr [ i + 1 ] ) nextpos [ i ] = nextpos [ i + 1 ] ; else nextpos [ i ] = i + 1 ; } } static void findIndex ( int query [ ] [ ] , int arr [ ] , int N , int Q ) { int [ ] nextpos = new int [ N ] ; precompute ( nextpos , arr , N ) ; for ( int i = 0 ; i < Q ; i ++ ) { int l , r , x ; l = query [ i ] [ 0 ] ; r = query [ i ] [ 1 ] ; x = query [ i ] [ 2 ] ; int ans = - 1 ; if ( arr [ l ] != x ) ans = l ; else { int d = nextpos [ l ] ; if ( d <= r ) ans = d ; } System . out . print ( ans + "NEW_LINE"); } } public static void main ( String [ ] args ) { int N , Q ; N = 6 ; Q = 3 ; int arr [ ] = { 1 , 2 , 1 , 1 , 3 , 5 } ; int query [ ] [ ] = { { 0 , 3 , 1 } , { 1 , 5 , 2 } , { 2 , 3 , 1 } } ; findIndex ( query , arr , N , Q ) ; } }