Here is the interview question prompt, presented for reference.
Given an array of positive and negative integers like the following:
const 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:
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:
let arr = [3, 5, -2, -4, 7, -1, 6, 8, -8, 4]
findSumZeroSubsets(arr);
// [[2, 5], [7, 8]]
// From 2 to 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:
arr = [4, -5, 1, -3, 2, -8, 5, -2, 9]
findSumZeroSubsets(arr);
// [[0, 2], [2, 4]]
// From 0 to 2
// From 2 to 4
100000
-1000
and 1000
O(n)
O(n)
You can see the full challenge with visuals at this link.
Challenges • Asked about 5 years ago by Thomas Hansen
This is the main discussion thread generated for Subsets Summing Zero.
Very cool! It might make sense for the hash to store a list of all the indexes where the value matched this way you print all subsets. As written, it won't print out some overlapping subsets.