3Sum

Medium

Topics
ArrayTwo PointersSorting

Given an integer array nums, return all unique triplets [a, b, c] that sum to 0. The result may be in any order and must not contain duplicate triplets.

Example 1

-10011223-14-45
One answer triplet is shaded: -1 + -1 + 2 = 0. The real work is skipping duplicates, since the answer is a set of triplets, not of index triples.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Example 2

000102
Input:  nums = [0,0,0]
Output: [[0,0,0]]

Constraints

  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Sort the array; then for each fixed first element, the remaining two-sum-to-target reduces to a two-pointer scan. Sorting also makes it easy to skip duplicates.

Approach

  1. Sort nums.
  2. For each index i (skipping duplicate values), two-pointer over the rest looking for sum 0.
  3. On a hit, record the triplet and advance both pointers past duplicates.

Dry Run

nums = [-1, 0, 1, 2, -1, -4]
sorted -> [-4, -1, -1, 0, 1, 2]
  i=0  fix -4, two-pointer over [-1, -1, 0, 1, 2]
       L=-1 R=2   sum -3 < 0   move L right
       L=-1 R=2   sum -3 < 0   move L right
       L= 0 R=2   sum -2 < 0   move L right
       L= 1 R=2   sum -1 < 0   move L right, pointers cross
  i=1  fix -1, two-pointer over [-1, 0, 1, 2]
       L=-1 R=2   sum  0       record [-1, -1, 2]
       L= 0 R=1   sum  0       record [-1, 0, 1]
  i=2  nums[2] == nums[1] == -1, skip
       without this skip, [-1, 0, 1] would be recorded a second time
  i=3  fix 0, two-pointer over [1, 2]
       L= 1 R=2   sum  3 > 0   move R left, pointers cross
  i=4, i=5   fewer than two elements remain
answer [-1, -1, 2] and [-1, 0, 1]
Sorting buys two unrelated things at once. It makes the two-pointer scan valid --
a sum that is too small can only be repaired by moving L right, never R -- and it
puts equal values side by side, which reduces duplicate suppression to a
comparison with the immediate predecessor.
There are two different duplicate skips and both are needed. The outer one at i=2
stops the same first element being fixed twice. The inner ones, after a match,
stop the same pair being recorded twice on input like [0,0,0,0]. On this array the
inner skips never fire -- the two matches land on distinct values -- so the trace
exercises only one of the two.

Complexity

  • Time — O(n^2): an O(n) two-pointer scan for each of n first elements.
  • Space — O(log n) to O(n), and the sort is the only reason: the two-pointer scan itself holds three indices, so O(1). Sorting is not free, though, and "O(1) ignoring the sort" is the answer interviewers push back on. Arrays.sort(int[]) in Java and std::sort in C++ are in-place quicksort variants that still recurse, so they cost O(log n) of stack; Python's list.sort() is Timsort, which allocates a merge buffer and costs O(n). The output list is excluded by convention, since it is the answer rather than working memory.

Common Pitfalls

  • Skip duplicate values at i and after each match to avoid duplicate triplets.

Full Solution — all languages

class Solution:
    def threeSum(self, nums):
        nums.sort()
        res=[]
        n=len(nums)
        for i in range(n):
            if i>0 and nums[i]==nums[i-1]: continue
            left,right=i+1,n-1
            while left<right:
                s=nums[i]+nums[left]+nums[right]
                if s==0:
                    res.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
                elif s<0: left+=1
                else: right-=1
        return res
SensAI
Beta
Tap the mic to stop voice mode