Number of indexes with equal elements in given range | C # program to count the number of indexes in range L R such that Ai = Ai + 1 ; array to store count of index from 0 to i that obey condition ; precomputing prefixans [ ] array ; traverse to compute the prefixans [ ] array ; function that answers every query in O ( 1 ) ; Driver Code ; pre - computation ; 1 - st query ; 2 nd query
using System ; class GFG { static int N = 1000 ; static int [ ] prefixans = new int [ N ] ; static void countIndex ( int [ ] a , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] == a [ i + 1 ] ) prefixans [ i ] = 1 ; if ( i != 0 ) prefixans [ i ] += prefixans [ i - 1 ] ; } } static int answer_query ( int l , int r ) { if ( l == 0 ) return prefixans [ r - 1 ] ; else return prefixans [ r - 1 ] - prefixans [ l - 1 ] ; } static void Main ( ) { int [ ] a = new int [ ] { 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 } ; int n = a . Length ; countIndex ( a , n ) ; int L , R ; L = 1 ; R = 8 ; Console . WriteLine ( answer_query ( L , R ) ) ; L = 0 ; R = 4 ; Console . WriteLine ( answer_query ( L , R ) ) ; } }