Number of indexes with equal elements in given range | CPP program to count the number of indexes in range L R such that Ai = Ai + 1 ; function that answers every query in O ( r - l ) ; traverse from l to r and count the required indexes ; Driver Code ; 1 - st query ; 2 nd query
#include <bits/stdc++.h> NEW_LINE using namespace std ; int answer_query ( int a [ ] , int n , int l , int r ) { int count = 0 ; for ( int i = l ; i < r ; i ++ ) if ( a [ i ] == a [ i + 1 ] ) count += 1 ; return count ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int L , R ; L = 1 ; R = 8 ; cout << answer_query ( a , n , L , R ) << endl ; L = 0 ; R = 4 ; cout << answer_query ( a , n , L , R ) << endl ; return 0 ; }