CODING CHALLENGE · N°28

3Sum

Medium Two PointersArraysInterview Classic

The rite of passage: find every unique triplet summing to zero without drowning in duplicates or O(n³). Sort once, fix one element, and let two pointers squeeze the rest — the pattern that generalizes to a whole family of k-sum problems.

The problem

Given nums, return all unique triplets [a, b, c] with a + b + c = 0. Each triplet must be sorted ascending, the list of triplets sorted lexicographically, and no triplet may appear twice — even if the input contains duplicates.

EXAMPLE 1
Input nums = [-1, 0, 1, 2, -1, -4]
Output [[-1, -1, 2], [-1, 0, 1]]
the duplicate -1 creates one extra triplet, not two copies
EXAMPLE 2
Input nums = [0, 0, 0, 0]
Output [[0, 0, 0]]
once, not four times
EXAMPLE 3
Input nums = [1, 2, 3]
Output []
no zero-sum triplet
CONSTRAINTS
  • Triplets sorted ascending internally; the result list sorted lexicographically.
  • No duplicate triplets in the output.
  • Target O(n²): sort + fixed element + two pointers, not three nested loops.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement three_sum(nums) → all unique zero-sum triplets, using sort + two pointers and duplicate-skipping at every level.

HINTS — 4 IDEAS
  1. Sort first. Sorted order is what makes both the two pointers AND the dedup possible.
  2. Fix index i; find pairs in nums[i+1:] summing to -nums[i] with left/right pointers.
  3. Sum too small → move left up; too big → move right down; equal → record and move BOTH.
  4. Skip duplicates three times: at i, at left after a hit, at right after a hit.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.