Number of indexes with equal elements in given range | JavaScript 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
const N = 1000 ; let prefixans = new Uint8Array ( N ) ; function countIndex ( a , n ) { for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == a [ i + 1 ] ) prefixans [ i ] = 1 ; if ( i != 0 ) prefixans [ i ] += prefixans [ i - 1 ] ; } } function answer_query ( l , r ) { if ( l == 0 ) return prefixans [ r - 1 ] ; else return prefixans [ r - 1 ] - prefixans [ l - 1 ] ; } let a = [ 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 ] ; let n = a . length ; countIndex ( a , n ) ; let L , R ; L = 1 ; R = 8 ; document . write ( answer_query ( L , R ) + " " ) ; L = 0 ; R = 4 ; document . write ( answer_query ( L , R ) + " " ) ;