mediumHash TableTwo PointersTwo Pointers

4Sum

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

Signals to notice

find all unique quadruplets summing to targetextension of 3Sumavoid duplicates

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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