You are given an array of integers. You need to print the total count of sub-arrays having their sum equal to 0. |
Example:
Input:
2
6
0 0 5 5 0 0
10
6 -1 -3 4 -2 2 4 6 -12 -7
Output:
6
4
Input:
2
6
0 0 5 5 0 0
10
6 -1 -3 4 -2 2 4 6 -12 -7
Output:
6
4
Here is a simple and easy solution using unordered_map :
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
unordered_map<int,int> mp;
int a[n],cnt=0,sum=0;
for(int i=0;i<n;++i)
{
cin>>a[i];
sum+=a[i];
if(sum==0)
++cnt;
cnt+=mp[sum];
mp[sum]++;
}
cout<<cnt<<endl;
}
return 0;
}