mediumHash TableTwo PointersTwo Pointers

4Sum

mediumTime: O(n^3)Space: O(n)

Recognize the pattern

find all unique quadruplets summing to targetextension of 3Sumavoid duplicates

Brute force idea

A straightforward first read of 4Sum is this: Four nested loops. Checks every possible quadruplet. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

A calmer way to see 4Sum is this: Sort, fix two elements (i, j), two-pointer scan for the other two. Skip duplicates at each level. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The compass for 4Sum is this: Sort first, then fix outer two elements. For the remaining two, use the two-pointer technique on the sorted remainder. Duplicate skipping at every level prevents repeated quadruplets. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in 4Sum is this: Not skipping duplicates at EVERY level — you need to skip at the i, j, left, AND right pointer levels to avoid duplicate quadruplets. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Two Pointers Pattern