Practice · Two pointers · 4 of 5

Three Numbers That Sum to Zero

You are given a list of integers nums. Return every triple of values [a, b, c] with a + b + c = 0, where the three values come from three different positions in nums.

List each triple of values only once: two triples holding the same three values (in any order) count as the same. Return the triples in any order, with the values inside each triple in any order.

Example 1

Input
nums = [-3, 1, 2, 0, -1, 3]
Output
[[-3, 0, 3], [-3, 1, 2], [-1, 0, 1]]

Example 2

Input
nums = [2, -1, -1, 0]
Output
[[-1, -1, 2]]
The two -1s sit at different positions, so a triple can use both.

Example 3

Input
nums = [0, 0, 0, 0]
Output
[[0, 0, 0]]
Many choices of three positions give 0, 0, 0, but it is listed once.

Constraints

  • nums holds 3 to 3000 numbers.
  • Every number is between −10⁵ and 10⁵.