Skip to content

3Sum

Find every distinct triplet that sums to zero, by sorting and running two pointers for each first number.

MediumTwo Pointers
Solve on LeetCode

The problem

You get an integer array nums. Return every distinct triplet [a, b, c] made of numbers at three different positions with a + b + c = 0. The answer must not contain the same triplet twice; the order of the triplets, and of the numbers inside each, doesn't matter.

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

Output [[-3, 0, 3], [-2, -1, 3], [-1, 0, 1]]

These are the only three ways to pick three of the numbers that add up to 0.

Input nums = [2, -1, -1, 2, -1]

Output [[-1, -1, 2]]

Many choices of positions give -1, -1 and 2, but the triplet is listed once.

Key constraint: The array can hold up to 3,000 numbers, so trying every triple (about 4.5 billion) is too slow, while O(n^2) is fine.

How to spot the pattern

  • You need groups of numbers with a fixed sum, and the answer must not repeat.
  • Once the array is sorted, fixing one number turns the rest into Two Sum II.
  • Sorting also puts equal values side by side, which makes skipping repeats easy.

The idea

Sort the array first. Then fix the first number nums[i] and look for two numbers after it that sum to -nums[i]; in a sorted range that is exactly Two Sum II, solved with two pointers moving inward. Equal values sit next to each other after sorting, so skipping repeats for i, and for both pointers after a match, keeps every triplet unique.

Brute force: Try every triple of positions and keep sorted triplets in a set to drop repeats, which takes O(n^3) time.

Step by step

  1. 1Sort nums.
  2. 2For each index i, stop once nums[i] > 0, and skip i if nums[i] equals nums[i - 1].
  3. 3Set left = i + 1 and right = n - 1, and compute sum = nums[i] + nums[left] + nums[right].
  4. 4If sum < 0, move left right; if sum > 0, move right left.
  5. 5If sum == 0, record the triplet, then move both pointers inward past any repeats of the values just used.

See the pattern move

The two pointers pattern on a small example. Step through it, or press play.

Code

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        result = []
        for i in range(n - 2):
            if nums[i] > 0:
                break  # three positive numbers can't add up to 0
            if i > 0 and nums[i] == nums[i - 1]:
                continue  # same first number as last time
            left, right = i + 1, n - 1
            while left < right:
                total = nums[i] + nums[left] + nums[right]
                if total < 0:
                    left += 1
                elif total > 0:
                    right -= 1
                else:
                    result.append([nums[i], nums[left], nums[right]])
                    left += 1
                    right -= 1
                    while left < right and nums[left] == nums[left - 1]:
                        left += 1
                    while left < right and nums[right] == nums[right + 1]:
                        right -= 1
        return result

Complexity

Time

O(n^2)

Space

O(1)

Sorting takes O(n log n), and each first number gets one O(n) pass of the two pointers. Apart from the output, the only extra memory is the sort's own workspace, from O(log n) to O(n) depending on the language.

Watch out for

  • Skipping repeats of the first number by comparing nums[i] with nums[i + 1] instead of nums[i - 1], which throws away triplets like [-1, -1, 2] where the repeat is part of the answer.
  • Forgetting to skip repeated values after a match, so the same triplet is added more than once.

Follow-up questions

How would you solve 3Sum Closest, where you want the sum nearest to a target?

Same sort and two pointers, but track the sum with the smallest distance to the target, and move the pointers by comparing the sum with the target instead of with 0.

What about 4Sum?

Add one more outer loop: fix two numbers, then run the two-pointer search on the rest, for O(n^3). Use 64-bit sums there, because four large ints can overflow.

In Hinglish

Pehle sort karo, ek number fix karo, aur baaki ke liye Two Sum II wale do pointers chalao; duplicates skip karna mat bhoolna.

Related problems