text: Count of subarrays having sum equal to its length | Set 2 | C ++ program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfSubarray ( int arr [ ] , int N ) { unordered_map < int , int > mp ; int answer = 0 ; int sum = 0 ; mp [ 1 ] ++ ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; answer += mp [ sum - i ] ; mp [ sum - i ] ++ ; } cout << answer ; } int main ( ) { int arr [ ] = { 1 , 0 , 2 , 1 , 2 , -2 , 2 , 4 } ; int N = sizeof arr / sizeof arr [ 0 ] ; countOfSubarray ( arr , N ) ; return 0 ; }