TRT
Sign in
mediumAdvancedLeetCode#sort#fix one, two pointers#skip duplicates

3Sum

Find every unique triple that sums to zero by fixing one value and running a two-pointer scan on the rest.

The Runtime Theory Team1 min read
Taught inTwo pointersPro — members onlyOn a sorted array, two indexes moving toward each other can find pairs with a given sum in one pass, because every move rules out a whole row of candidate pairs. The same argument powers three-sum, container problems and trapping rain water.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [-1, 0, 1, 2, -1, -4]

out[[-1, -1, 2], [-1, 0, 1]]

innums = [0, 1, 1]

out[]

innums = [0, 0, 0]

out[[0, 0, 0]]

Return all triples [a, b, c] from the array, at distinct positions, with a + b + c = 0. The result must not contain duplicate triples.

Before you code

Checking every triple is O(n³). After sorting, fixing the first value reduces the rest to Two sum II on a sorted range: O(n²) in total.

Hints

  1. Sort. For each i, run two pointers on i + 1 to the end, looking for -nums[i].
  2. Skip nums[i] if it equals nums[i - 1].
  3. After recording a triple, move both pointers past equal values.
  4. Stop early when nums[i] > 0: no triple starting there can sum to zero.

Production & complexity notes

When solving 3Sum on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers to reinforce the underlying pattern.

What it practices

Extending two pointers and avoiding duplicates without a set, from Two pointers.

Not started

Sign in to save your learning progress.

Sign in to save