Count of subarrays having sum equal to its length | Set 2 | Function that counts the subarrays with sum of its elements as its length ; Store count of elements upto current element with length i ; Stores the final count of subarray ; Stores the prefix sum ; If size of subarray is 1 ; Iterate the array ; Find the sum ; Update frequency in map ; Print the total count ; Given array arr [ ] ; Size of array ; Function Call
function countOfSubarray ( arr , N ) { var mp = new Map ( ) ; var answer = 0 ; var sum = 0 ; if ( ! mp . has ( 1 ) ) mp . set ( 1 , 1 ) else mp . set ( 1 , mp . get ( 1 ) + 1 ) for ( var i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; answer += mp . has ( sum - i ) ? mp . get ( sum - i ) : 0 ; if ( mp . has ( sum - i ) ) mp . set ( sum - i , mp . get ( sum - i ) + 1 ) else mp . set ( sum - i , 1 ) } document . write ( answer ) ; } var arr = [ 1 , 0 , 2 , 1 , 2 , - 2 , 2 , 4 ] ; var N = arr . length ; countOfSubarray ( arr , N ) ;