100 XP

80. Three that add to zero

Advanced two pointers sorting

Write a function three_sum(numbers) that takes a list of whole numbers and returns every different triple of them that adds up to 0:

  • A triple uses three different positions of the list, but the values can repeat when the list has them: [0, 0, 0] needs three 0s in the list.
  • Each triple is written with its numbers from smallest to largest, like [-2, 0, 2].
  • Two triples with the same values are the same triple: list it once, however many ways the list can make it.
  • The list of triples is sorted from smallest to largest, comparing first numbers, then second (as Python's sorted() does). No triple at all gives [].

Checking every three positions takes about n³/6 steps. After sorting, two pointers find the pairs for each first number in one pass.

Example 1

Inputnumbers = [-2, 0, 1, 1, 2]
Output[[-2, 0, 2], [-2, 1, 1]]
Explanation-2 + 0 + 2 and -2 + 1 + 1 are both 0.

Example 2

Inputnumbers = [0, 0, 0, 0]
Output[[0, 0, 0]]
ExplanationMany ways to pick three 0s, one triple.

Example 3

Inputnumbers = [1, 2, -2]
Output[]
Explanation1 + 2 - 2 is 1, not 0.

Constraints

  • numbers has 0 to 100 whole numbers, each from -1000 to 1000.

Submit also runs 9 more tests you can't see.

Code
def three_sum(numbers):
    """Find every different triple that adds up to 0.

    numbers: list of int; may be empty
    Returns: list of [a, b, c] with a <= b <= c and
        a + b + c == 0, each once, sorted
    """
    # Write your code here
    pass