Skip to content
Problem 15 · LeetCode 15(opens in a new tab)

3Sum

MediumArrays

You are given a list of whole numbers, nums. Find every group of three numbers, taken from three different positions, whose total is exactly 0.

Each group is a triplet of values. Return each distinct triplet once: two triplets with the same three values count as the same, even if they come from different positions. The triplets, and the numbers inside each one, can be in any order.

Example 1

Input:  nums = [2, -3, 1, 0, -1, 1]
Output: [[-3, 1, 2], [-1, 0, 1]]
Why:    -3 + 1 + 2 = 0 and -1 + 0 + 1 = 0; the second 1 adds no new triplet
2 more examples and the constraints

Example 2

Input:  nums = [1, 2, -4]
Output: []
Why:    the only triplet adds up to -1

Example 3

Input:  nums = [0, 0, 0, 0]
Output: [[0, 0, 0]]
Why:    four zeros give many position triples but one triplet of values

Constraints

  • 3 ≤ length of nums ≤ 3,000
  • Every number is between −100,000 and 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every triple + a setO(n³)
  2. Sort + two pointersO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 3,000 numbersVerdict
Every triple + a setO(n³)
Correct, far too slow
Sort + two pointersO(n²)
Best; the expected answer

n = how many numbers are in the list, t = how many distinct triplets there are.

Edge cases to test

  • Repeated values. [2, -3, 1, 0, -1, 1] has two 1s, but [-3, 1, 2] must appear once.
  • All zeros. [0, 0, 0, 0] gives exactly one triplet, [0, 0, 0].
  • No answer. [1, 2, -4] or a list of only positive numbers returns an empty list.
  • Two equal values in one triplet. [-100000, 50000, 50000] is valid: the 50,000s sit at different positions.

Common mistakes

  • Skipping a repeated first value by comparing with the next one instead of the previous one, which loses triplets like [-1, -1, 2].
  • Forgetting to move a pointer after a hit, so the loop never ends.
  • Removing duplicates at the end with a set of unsorted lists, where [1, -1, 0] and [-1, 0, 1] look different.

How to talk through it

  1. 1Clarify. Can values repeat? Does the order of triplets or of numbers inside one matter? What do I return when nothing works?
  2. 2Give the brute force. Every triple plus a set for repeats; say it is O(n³) and too slow for 3,000 numbers.
  3. 3Reduce to Two Sum. Fix one number, then I need a pair that adds to its negative. On a sorted list that is a two-pointer walk.
  4. 4Handle duplicates by skipping. Sorting puts copies side by side, so I skip a first value I have used and move L past copies after a hit.
  5. 5Test out loud. Run the all-zeros and repeated-values cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?