Skip to content

Commit 258feb0

Browse files
Added solution
1 parent d7f8a76 commit 258feb0

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

amazon/zero_sum_subarrays.cpp

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int mod=1e9+7;
5+
#define F(a,b,var) for(int var=a;var<b;var++)
6+
#define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL)
7+
8+
/*
9+
You are given an array A of size N.
10+
You need to print the total count of sub-arrays having their sum equal to 0
11+
For each test case, in a new line, print the total number of subarrays whose sum is equal to 0.
12+
13+
Constraints:
14+
1 <= T <= 100
15+
1<= N <= 107
16+
-1010 <= Ai <= 1010
17+
18+
Example:
19+
Input:
20+
2
21+
6
22+
0 0 5 5 0 0
23+
10
24+
6 -1 -3 4 -2 2 4 6 -12 -7
25+
26+
Output:
27+
6
28+
4
29+
*/
30+
31+
32+
int main()
33+
{
34+
//code
35+
36+
FAST_INP;
37+
int T;
38+
cin>>T;
39+
while(T--)
40+
{
41+
int n, c; cin>>n;
42+
vector<int> sub_array_test;
43+
for(int i = 0; i < n; i++){
44+
int curr;
45+
cin>>curr;
46+
sub_array_test.push_back(curr);
47+
}
48+
49+
50+
/*
51+
maintain global sum = 0
52+
use hashmap that maps the current sum to vector of pairs or end index... map<int, vector<int>>
53+
54+
if sum(arr[0...i]) == 0 and sum(arr[0...j]) == 0
55+
then there exists a sub-array arr[i+1]...arr[j] whose sum is 0
56+
*/
57+
// initialisations
58+
59+
unordered_map<int, int> sub_array_mp;
60+
int curr_sum = 0, zero_count = 0;
61+
62+
//o(n)
63+
for(int i = 0; i < sub_array_test.size(); i++){
64+
curr_sum += sub_array_test[i]; //cummulative sum
65+
66+
if(curr_sum == 0) // indicates that there exists a pair from 0 to i
67+
zero_count++;
68+
69+
if(sub_array_mp[curr_sum] != 0) // a pair exists whose sum == 0 is already discovered
70+
zero_count += sub_array_mp[curr_sum];
71+
72+
sub_array_mp[curr_sum]++;
73+
}
74+
cout<<zero_count<<"\n";
75+
}
76+
return 0;
77+
}

0 commit comments

Comments
 (0)