L3 · FAANGTwo pointers~20 min · 6 tests

3Sum: Triplets That Sum to Zero

Find every unique triplet that sums to zero by sorting and squeezing two pointers in O(n²), skipping duplicates. A FAANG favourite, run in your browser.

The problem

Return every unique triplet [a, b, c] from nums with a + b + c == 0. Write each triplet in ascending order; the list of triplets may be in any order.

Examples

  1. Example 1

    Input

    three_sum([-1, 0, 1, 2, -1, -4])

    Expected output

    [[-1, -1, 2], [-1, 0, 1]]
  2. Example 2

    Input

    three_sum([0, 0, 0, 0])

    Expected output

    [[0, 0, 0]]

+ 4 hidden tests on Submit.

Edge cases to ask about

  • All zeros
  • No solution
  • Many duplicates

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · three_sum
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 200 up to 3,200 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Three nested loops + setO(n³)O(n)
    Fix one, hash-set two-sumO(n²)O(n)Dedupe is messier.
    bestSort + two pointersO(n²)O(1) extraSorting makes duplicate-skipping trivial.
    Walkthrough of the optimal approach (try it yourself first)

    Sort first. For each anchor nums[i], look for pairs in nums[i+1:] summing to -nums[i] with two pointers: too small → move lo right, too big → move hi left.

    Duplicates are the real difficulty. Skip an anchor equal to the previous one, and after recording a triplet advance lo past equal values. Once the anchor is positive, no later triplet can sum to zero, so you can stop.

    Complexity: O(n²) time, O(1) space. Sorting is O(n log n); then for each of n anchors the two pointers sweep the rest in O(n). Extra space is O(1) beyond the sorted copy and the output.

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

    The brute force, for comparison

    def three_sum(nums):
        found = set()
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                for k in range(j + 1, n):
                    if nums[i] + nums[j] + nums[k] == 0:
                        found.add(tuple(sorted((nums[i], nums[j], nums[k]))))
        return [list(t) for t in found]

    Follow-ups interviewers ask

    • 3Sum closest to a target.
    • 4Sum / k-Sum generalisation.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of 3Sum: Triplets That Sum to Zero in Python?

    The optimal solution runs in O(n²) time and O(1) auxiliary space. Sorting is O(n log n); then for each of n anchors the two pointers sweep the rest in O(n). Extra space is O(1) beyond the sorted copy and the output.

    What is the brute-force approach, and how do you optimise it?

    Three nested loops + set: O(n³) time, O(n) space. Fix one, hash-set two-sum: O(n²) time, O(n) space. Dedupe is messier. Sort + two pointers: O(n²) time, O(1) extra space. Sorting makes duplicate-skipping trivial.

    What follow-up questions do interviewers ask about 3Sum: Triplets That Sum to Zero?

    3Sum closest to a target. 4Sum / k-Sum generalisation.