Number of indexes with equal elements in given range | Python 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 ; def that answers every query in O ( 1 ) ; Driver Code ; pre - computation ; 1 - st query ; 2 nd query
N = 1000 NEW_LINE prefixans = [ 0 ] * N ; NEW_LINE def countIndex ( a , n ) : NEW_LINE INDENT global N , prefixans NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 1 ] ) : NEW_LINE INDENT prefixans [ i ] = 1 NEW_LINE DEDENT if ( i != 0 ) : NEW_LINE INDENT prefixans [ i ] = ( prefixans [ i ] + prefixans [ i - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def answer_query ( l , r ) : NEW_LINE INDENT global N , prefixans NEW_LINE if ( l == 0 ) : NEW_LINE INDENT return prefixans [ r - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return ( prefixans [ r - 1 ] - prefixans [ l - 1 ] ) NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 ] NEW_LINE n = len ( a ) NEW_LINE countIndex ( a , n ) NEW_LINE L = 1 NEW_LINE R = 8 NEW_LINE print ( answer_query ( L , R ) ) NEW_LINE L = 0 NEW_LINE R = 4 NEW_LINE print ( answer_query ( L , R ) ) NEW_LINE