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 program to test above
function countSubarrWithEqualZeroAndOne ( arr , n ) { var um = new Map ( ) ; var curr_sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) { curr_sum += ( arr [ i ] == 0 ) ? - 1 : arr [ i ] ; if ( um . has ( curr_sum ) ) um . set ( curr_sum , um . get ( curr_sum ) + 1 ) ; else um . set ( curr_sum , 1 ) } var count = 0 ; um . forEach ( ( value , key ) => { if ( value > 1 ) count += ( ( value * ( value - 1 ) ) / 2 ) ; } ) ; if ( um . has ( 0 ) ) count += um . get ( 0 ) ; return count ; } var arr = [ 1 , 0 , 0 , 1 , 0 , 1 , 1 ] ; var n = arr . length ; document . write ( " " + countSubarrWithEqualZeroAndOne ( arr , n ) ) ;