Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Subsets Summing Zero (Main Thread)

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:

  1. 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.
  2. Subsequence: A subsequence is a non-empty subset that maintains the order of the elements according to the original array.
  3. 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:

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

Constraints

  • Length of the array <= 100000
  • The array will contain values between -1000 and 1000
  • Expected time complexity: O(n)
  • Expected space complexity: O(n)

You can see the full challenge with visuals at this link.

Challenges • Asked about 5 years ago by Thomas Hansen

Jake from AlgoDaily Commented on Sep 12, 2019:

This is the main discussion thread generated for Subsets Summing Zero.

Thomas Hansen Commented on Sep 12, 2019:

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.