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