text: Smallest index in given range of indices which is not equal to X | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } } void findIndex ( int query [ ] [ 3 ] , int arr [ ] , int N , int Q ) { int nextpos [ 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 ; } cout << ans << " STRNEWLINE " ; } } int main ( ) { int N , Q ; N = 6 ; Q = 3 ; int arr [ ] = { 1 , 2 , 1 , 1 , 3 , 5 } ; int query [ Q ] [ 3 ] = { { 0 , 3 , 1 } , { 1 , 5 , 2 } , { 2 , 3 , 1 } } ; findIndex ( query , arr , N , Q ) ; return 0 ; }