File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ Given an Array of size N, identify whether there exists a subarray with zero sum?
2
+
3
+ Conditions: -10^6<=N<=10^6
4
+ Time limit is 1.0 sec
Original file line number Diff line number Diff line change
1
+ /* C++ Solution */
2
+
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ /* Function to check whether zero sum subarray exists or not*/
7
+ bool hasZeroSum (int arr[], int N)
8
+ {
9
+ set<int > st;
10
+ int sum=0 ;
11
+ for (int i=0 ;i<N;i++)
12
+ {
13
+ sum+=arr[i];
14
+ /* if Set contains a sum already,
15
+ that means zero sum subArray exists*/
16
+ if (st.find (sum)!=st.end ()||sum==0 )
17
+ return true ;
18
+
19
+ st.insert (sum);
20
+ }
21
+ return false ;
22
+ }
23
+
24
+ int main () {
25
+ int N;
26
+ cin>>N;
27
+ int arr[N+1 ];
28
+
29
+ // Array input
30
+ for (int i=0 ;i<N;i++)
31
+ cin>>arr[i];
32
+
33
+
34
+ bool ans = hasZeroSum (arr,N);
35
+ cout<<ans;
36
+ return 0 ;
37
+ }
You can’t perform that action at this time.
0 commit comments