-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZero_Sum_Subarrays.cpp
56 lines (43 loc) · 1.18 KB
/
Zero_Sum_Subarrays.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//{ Driver Code Starts
//Initial function template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
//Function to count subarrays with sum equal to 0.
long long int findSubarray(vector<long long int> &A, int N) {
unordered_map<long long int, int> prefixSum;
long long int sum = 0;
long long int cnt = 0;
for(int i = 0; i < N; i++)
{
sum += A[i];
if(sum == 0)
cnt++;
if(prefixSum.find(sum) != prefixSum.end())
cnt += prefixSum[sum];
prefixSum[sum]++;
}
return cnt;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n; //input size of array
vector<long long int> arr(n,0);
for(int i=0;i<n;i++)
cin>>arr[i]; //input array elements
Solution ob;
cout << ob.findSubarray(arr,n) << "\n";
}
return 0;
}
// } Driver Code Ends