80. Three that add to zero
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
Input
numbers = [-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
Input
numbers = [0, 0, 0, 0]Output
[[0, 0, 0]]ExplanationMany ways to pick three 0s, one triple.
Example 3
Input
numbers = [1, 2, -2]Output
[]Explanation1 + 2 - 2 is 1, not 0.
Constraints
numbershas 0 to 100 whole numbers, each from -1000 to 1000.
Submit also runs 9 more tests you can't see.
- Sort the numbers. Then fix the first number of the triple,
a = nums[i], and look for two numbers after it that add up to-a. - For that pair use two pointers,
lo = i + 1andhiat the end: a total below 0 needs a bigger number (lo += 1), above 0 a smaller one (hi -= 1). - To list each triple once, skip an
aequal to the one before it, and after a match movelopast every copy of the number it found.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.