Skip to content

Commit 3667a5e

Browse files
committed
Subarray with 0 sum
1 parent 6feeee8 commit 3667a5e

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
- [Count pairs with given sum](https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1# "view question") - [Cpp Solution](./solutions/Count%20pairs%20with%20given%20sum.cpp)
2222
- [Common elements](https://practice.geeksforgeeks.org/problems/common-elements1132/1# "view question") - [Cpp Solution](./solutions/Common%20elements.cpp)
2323
- [Rearrange array in alternating positive & negative items with O(1) extra space](https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/ "view topic") - [Cpp Solution](./solutions/Rearrange%20array%20in%20alternating%20positive%20&%20negative%20items%20with%20O(1)%20extra%20space.cpp)
24+
- [Subarray with 0 sum](https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1# "view question") - [Cpp Solution](./solutions/Subarray%20with%200%20sum.cpp)
2425
- []( "view question") - [Cpp Solution](./solutions/.cpp)
2526

2627
<!-- - []( "view question") - [Cpp Solution](./solutions/) -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Subarray with 0 sum
3+
====================
4+
5+
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
6+
7+
Example 1:
8+
Input:
9+
5
10+
4 2 -3 1 6
11+
Output:
12+
Yes
13+
Explanation:
14+
2, -3, 1 is the subarray
15+
with sum 0.
16+
17+
Example 2:
18+
Input:
19+
5
20+
4 2 0 1 6
21+
Output:
22+
Yes
23+
Explanation:
24+
0 is one of the element
25+
in the array so there exist a
26+
subarray with sum 0.
27+
Your Task:
28+
You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.
29+
30+
Expected Time Complexity: O(n).
31+
Expected Auxiliary Space: O(n).
32+
33+
Constraints:
34+
1 <= N <= 104
35+
-105 <= a[i] <= 105
36+
*/
37+
38+
bool subArrayExists(int arr[], int n)
39+
{
40+
unordered_set<int> prefix_sums;
41+
int sum = 0;
42+
for (int i = 0; i < n; ++i)
43+
{
44+
sum += arr[i];
45+
if (!sum)
46+
return true;
47+
if (prefix_sums.find(sum) != prefix_sums.end())
48+
return true;
49+
prefix_sums.insert(sum);
50+
}
51+
return false;
52+
}

0 commit comments

Comments
 (0)