AlgoDaily

Subsets Summing Zero

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

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)
```js
function findSumZeroSubsets(arr) {}

console.log(findSumZeroSubsets([1, 2, 0, -3, -2]));
```

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →