Count subarrays with equal number of 1 ' s ▁ and ▁ 0' s | function to count subarrays with equal number of 1 ' s ▁ and ▁ 0' s ; ' um ' implemented as hash table to store frequency of values obtained through cumulative sum ; Traverse original array and compute cumulative sum and increase count by 1 for this sum in ' um ' . Adds ' - 1' when arr [ i ] == 0 ; traverse the hash table um ; If there are more than one prefix subarrays with a particular sum ; add the subarrays starting from 1 st element and have equal number of 1 ' s ▁ and ▁ 0' s ; required count of subarrays ; Driver code to test above
def countSubarrWithEqualZeroAndOne ( arr , n ) : NEW_LINE INDENT um = dict ( ) NEW_LINE curr_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sum += ( - 1 if ( arr [ i ] == 0 ) else arr [ i ] ) NEW_LINE if um . get ( curr_sum ) : NEW_LINE INDENT um [ curr_sum ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT um [ curr_sum ] = 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for itr in um : NEW_LINE INDENT if um [ itr ] > 1 : NEW_LINE INDENT count += ( ( um [ itr ] * int ( um [ itr ] - 1 ) ) / 2 ) NEW_LINE DEDENT DEDENT if um . get ( 0 ) : NEW_LINE INDENT count += um [ 0 ] NEW_LINE DEDENT return int ( count ) NEW_LINE DEDENT arr = [ 1 , 0 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Count ▁ = " , countSubarrWithEqualZeroAndOne ( arr , n ) ) NEW_LINE