Skip to content

Commit 04ec8fc

Browse files
committed
largest subarr sum 0
1 parent fde6890 commit 04ec8fc

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Largest subarray with 0 sum
3+
===========================
4+
5+
Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0.
6+
7+
Example 1:
8+
Input:
9+
N = 8
10+
A[] = {15,-2,2,-8,1,7,10,23}
11+
Output: 5
12+
Explanation: The largest subarray with
13+
sum 0 will be -2 2 -8 1 7.
14+
Your Task:
15+
You just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum.
16+
17+
Expected Time Complexity: O(N*Log(N)).
18+
Expected Auxiliary Space: O(N).
19+
20+
Constraints:
21+
1 <= N <= 104
22+
-1000 <= A[i] <= 1000, for each valid i
23+
*/
24+
25+
int maxLen(int A[], int n)
26+
{
27+
vector<int> prefix(n, 0);
28+
prefix[0] = A[0];
29+
for (int i = 1; i < n; ++i)
30+
prefix[i] = prefix[i - 1] + A[i];
31+
32+
unordered_map<int, int> m;
33+
int ans = 0;
34+
for (int i = 0; i < n; ++i)
35+
{
36+
if (prefix[i] == 0)
37+
ans = max(ans, i + 1);
38+
if (m.find(prefix[i]) != m.end())
39+
{
40+
ans = max(ans, i - m[prefix[i]]);
41+
}
42+
else
43+
m[prefix[i]] = i;
44+
}
45+
46+
return ans;
47+
}

Striver Sheet/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
- [Two Sum](https://leetcode.com/problems/two-sum/) - [Cpp Soultion](./Day-4/Two%20Sum.cpp)
3535
- [4Sum](https://leetcode.com/problems/4sum/) - [Cpp Soultion](./Day-4/4Sum.cpp)
3636
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) - [Cpp Soultion](./Day-4/Longest%20Consecutive%20Sequence.cpp)
37-
- []() - [Cpp Soultion](./Day-4/.cpp)
37+
- [Largest subarray with 0 sum](https://practice.geeksforgeeks.org/problems/largest-subarray-with-0-sum/1#) - [Cpp Soultion](./Day-4/Largest%20subarray%20with%200%20sum.cpp)
3838
- []() - [Cpp Soultion](./Day-4/.cpp)
3939
- []() - [Cpp Soultion](./Day-4/.cpp)
4040

0 commit comments

Comments
 (0)