Number of indexes with equal elements in given range | PHP 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
< ? php $ N = 1000 ; $ prefixans = array_fill ( 0 , $ N , 0 ) ; function countIndex ( $ a , $ n ) { global $ N , $ prefixans ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { if ( $ a [ $ i ] == $ a [ $ i + 1 ] ) $ prefixans [ $ i ] = 1 ; if ( $ i != 0 ) $ prefixans [ $ i ] += $ prefixans [ $ i - 1 ] ; } } function answer_query ( $ l , $ r ) { global $ N , $ prefixans ; if ( $ l == 0 ) return $ prefixans [ $ r - 1 ] ; else return ( $ prefixans [ $ r - 1 ] - $ prefixans [ $ l - 1 ] ) ; } $ a = array ( 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 ) ; $ n = count ( $ a ) ; countIndex ( $ a , $ n ) ; $ L = 1 ; $ R = 8 ; echo ( answer_query ( $ L , $ R ) . " " ) ; $ L = 0 ; $ R = 4 ; echo ( answer_query ( $ L , $ R ) . " " ) ; ? >