← Whiteboard questions

3Sum

Find all unique triples that add up to zero

DSA, Medium, Two Pointers

Which structure or algorithm, and what does it cost.

You get a list of integers nums. Find every set of three values, taken from three different positions, that add up to 0. Return each triple as a list in non-decreasing order. List the triples from smallest to largest, comparing first values, then second values. Each distinct triple appears once, even if several position sets build it. Return [] if there is none.

Examples

Input nums = [-4, 1, 3, 0, -1, 2, -2]
Output [[-4, 1, 3], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]]
Why four distinct triples add up to 0, each listed once in ascending order.
Input nums = [-3, -3, -3, 6, 6, 0]
Output [[-3, -3, 6]]
Why three -3s and two 6s still build one triple, and it is listed once.
Input nums = [5, -1]
Output []
Why a triple needs three positions, and the list has only two.

Constraints

Your answer must contain

Target Aim for O(n^2) time.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Fix one value first. What must the other two add up to? You may know that pair problem already.

Hint 2 the approach

Sort the list first. With one value fixed, what does the sorted order tell you when a pair sum is too small or too big?

Hint 3 the key step

Put a marker at each end of the part right of the fixed value, and move one by the sum. Then ask where the same triple can show up twice.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every set of three positions, sort each triple, and keep those that add up to 0 in a set so repeats drop out. That takes O(n^3) time. With 3,000 values it is about 4.5 billion sets, which is too slow.

Better method

Fix one value and find the other two with a hash set in one pass over the rest. This is O(n^2) time, but it needs a set for each fixed value and extra care to avoid repeated triples. The sorted method below is cleaner.

Best method

Sort a copy of the list. Fix the first value at each position i from left to right. The other two values lie to the right of i, so put a marker at each end of that part. Add the three values. If the sum is below 0, move the left marker up. If it is above 0, move the right marker down. If it is 0, record the triple, then move both markers inward and skip values on the left that repeat the one just used. Skip a fixed value that equals the previous one. Stop when the fixed value is above 0, because every later sum is positive. Each fixed value costs one linear scan, and the sort puts repeats side by side, so each distinct triple appears once. Use the same shape when a question asks for all tuples with a given sum: sort, fix all but two values, and run two markers.

Hand trace

Run on [-4, 1, 3, 0, -1, 2, -2]. The sorted list is [-4, -2, -1, 0, 1, 2, 3]. Fixed -4 with markers on -2 and 3: the sum is -3, so move the left marker up. With -1 and 3 the sum is -2, then with 0 and 3 it is -1, then with 1 and 3 it is 0, so record [-4, 1, 3]. Fixed -2 with -1 and 3: the sum is 0, so record [-2, -1, 3]. Then 0 and 2 also give 0, so record [-2, 0, 2]. Fixed -1 with 0 and 3 gives 2, so move the right marker down. With 0 and 2 it gives 1, then with 0 and 1 it gives 0, so record [-1, 0, 1]. Fixed 0 with 1 and 3 gives 4, then 1 and 2 gives 3, so nothing more. Fixed 1 is above 0, so stop. The result has four triples.

Code

def zero_triples(nums):
    a = sorted(nums)
    out = []
    for i in range(len(a) - 2):
        if a[i] > 0:
            break
        if i > 0 and a[i] == a[i - 1]:
            continue
        lo, hi = i + 1, len(a) - 1
        while lo < hi:
            s = a[i] + a[lo] + a[hi]
            if s < 0:
                lo += 1
            elif s > 0:
                hi -= 1
            else:
                out.append([a[i], a[lo], a[hi]])
                lo += 1
                hi -= 1
                while lo < hi and a[lo] == a[lo - 1]:
                    lo += 1
    return out

Time and memory

O(n^2) time: the sort is O(n log n), and each of the n fixed values runs a marker scan of at most n steps. O(n) extra memory for the sorted copy (O(1) if you may sort the input in place), not counting the answer.

Common mistakes

  • Not skipping a fixed value that repeats the one before it. With [0, 0, 0, 0] the triple [0, 0, 0] is listed more than once.
  • Skipping repeated values on the left before you record a hit. With [-3, -3, 6] the second -3 is skipped too early and the triple is lost.
  • Hiding repeats with a set of triples while keeping the O(n^3) search. The output is right, but the cost is not.

Related problems

More Two Pointers problems
3Sum: hints, walkthrough and Python solution