iq.lab
Python starts when a code cell comes near or you run one
mediumTwo pointersSorting target 25 min

Three sum

Not solved yetLeetCode 15. 3Sum

You get a list of integers nums. A triple here is three numbers taken from three different positions of nums. Return every triple whose three numbers add up to 0, as a list of lists of three numbers.

A triple is known by its values, not by its positions. [-1, 0, 1] and [0, 1, -1] are the same triple, and so are two triples that use different copies of a repeated value. List each triple once. The triples can come in any order, and so can the three numbers inside each one. If no triple adds up to 0, return an empty list.

Example 1
Inputnums = [-2, 0, 1, 1, 2]Output[[-2, 0, 2], [-2, 1, 1]]

-2 + 0 + 2 = 0 and -2 + 1 + 1 = 0. The two 1s sit at different positions, so one triple can use both.

Example 2
Inputnums = [2, -3, 1, -3, 0, 1]Output[[-3, 1, 2]]

Two -3s and two 1s give four ways to pick positions for -3 + 1 + 2, but it is one triple of values, listed once.

Example 3
Inputnums = [4, -1, 5]Output[]

The only triple adds up to 8.

Constraints
  • 0 ≤ len(nums) ≤ 3,000

  • -105 ≤ nums[i] ≤ 105

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.