Count of subarrays having sum equal to its length | Function that counts the subarrays with sum of its elements as its length ; Decrementing all the elements of the array by 1 ; Making prefix sum array ; Declare map to store count of elements upto current element ; To count all the subarrays whose prefix sum is 0 ; Iterate the array ; Increment answer by count of current element of prefix array ; Return the answer ; Given array arr [ ] ; Function call
function countOfSubarray ( arr , N ) { for ( let i = 0 ; i < N ; i ++ ) arr [ i ] -- ; let pref = [ ] ; pref [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < N ; i ++ ) pref [ i ] = pref [ i - 1 ] + arr [ i ] ; let mp = new Map ; let answer = 0 ; if ( mp [ 0 ] ) mp [ 0 ] ++ ; else mp [ 0 ] = 1 ; for ( let i = 0 ; i < N ; i ++ ) { if ( mp [ pref [ i ] ] ) { answer += mp [ pref [ i ] ] ; mp [ pref [ i ] ] ++ ; } } return answer ; } let arr = [ 1 , 1 , 0 ] ; let N = arr . length ; document . write ( countOfSubarray ( arr , N ) ) ;