Good morning! Here's our prompt for today.
Given an array of positive and negative integers like the following:
1const arr = [3, 5, -2, -4, 7, -1, 6, 8, -8, 4];
Can you write a method findSumZeroSubsets
to return the starting and ending indexes of all subarrays in it that sum up to zero?
Note: There are 3 terms that you should be able to distinguish when in the context of arrays. Those are:
- Subset: A subset of an array is what it says exactly, a piece of a larger set. It is not ordered and not contiguous. Bear in mind that there can be empty subsets of an array.
- Subsequence: A subsequence is a non-empty subset that maintains the order of the elements according to the original array.
- Subarray: A non-empty subset of an array that is contiguous.
Note that in this challenge, we are using the terms subset
and subarray
interchangeable, but are always referring to the definition of contiguous subarray.
Let's take the following example for the original problem:

1let arr = [3, 5, -2, -4, 7, -1, 6, 8, -8, 4]
2findSumZeroSubsets(arr);
3// [[2, 5], [7, 8]]
4// From 2 to 5
5// From 7 to 8
We log out From 2 to 5
because from index 2
to 5
, the elements are [-2, -4, 7, -1]
, which sum up to 0
. Similarly, indices 7
and 8
are 8
and -8
respectively, which also sum up to 0
. Here's another example:
1arr = [4, -5, 1, -3, 2, -8, 5, -2, 9]
2findSumZeroSubsets(arr);
3// [[0, 2], [2, 4]]
4// From 0 to 2
5// From 2 to 4
Constraints
- Length of the array <=
100000
- The array will contain values between
-1000
and1000
- Expected time complexity:
O(n)
- Expected space complexity:
O(n)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
​
def find_sum_zero_subsets(arr):
# fill in
return result
​
​
# print(find_sum_zero_subsets([1, 2, 0, -3, -2]))
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert callable(find_sum_zero_subsets) == True
print("PASSED: find_sum_zero_subsets is a function")
​
def test_2(self):
assert find_sum_zero_subsets([3, 5, -2, -4, 7, -1, 6, 8, -8, 4]) == [
[2, 5],
[7, 8],
]
print(
"PASSED: find_sum_zero_subsets([3, 5, -2, -4, 7, -1, 6, 8, -8, 4]) should return [[2, 5], [7, 8]]"
)
​
def test_3(self):
assert find_sum_zero_subsets([4, -5, 1, -3, 2, -8, 5, -2, 9]) == [
[0, 2],
[2, 4],
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

We'll now take you through what you need to know.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.