Zero Sum Subarray

A corgi smiling happily

You’re given a list of integers nums. Write a function that returns a boolean representing whether there exists a zero-sum subarray of nums.

A zero-sum subarray is any subarray where all the values add up to zero. A subarray is any contiguous section of the array. For the purposes of this problem, a subarray can be as small as one element and as long as the original array.

Sample Input

1nums = [-5, -5, 2, 3, -2]

Sample Output

1True // The subarray [-5, 2, 3] has a sum of 0

Hints

Hint 1

A good way to approach this problem is to first think of a simpler version. How would you check if the entire array sum is zero?

Hint 2

If the entire array does not sum to zero, then you need to check if there are any smaller sub-arrays that sum to zero. For this, it can be helpful to keep track of all the sums from [0, i], where i is every index in the array.

Hint 3

After recording all sums from [0, i], what would it mean if a sum is repeated?

Optimal Space & Time Complexity

O(n) time | O(n) space - where n is the length of nums

Solution-1
1function zeroSumSubarray(nums) {
2
3 for (let i = 0; i < nums.length; i++) {
4 let sum = nums[i]
5 if (sum === 0) {
6 return true
7 }
8
9 for (let j = i + 1; j < nums.length; j++) {
10 sum = sum + nums[j]
11 if (sum === 0) {
12 console.log(nums[i], nums[j])
13 return true
14 }
15 }
16 }
17
18 return false;
19}
Solution-2
1function zeroSumSubarray(nums) {
2 // Write your code here.
3 const sums = new Set([0])
4 let currentSum = 0
5 for (const num of nums) {
6 currentSum += num
7 if(sums.has(currentSum)) return true
8 sums.add(currentSum)
9 }
10 return false
11}

🧝‍♂️

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.