◀ THE GRIND — TWO POINTERS

4Sum

MEDIUM✓ CHIP-TIMEDLC #18 — FULL STATEMENT ↗

The drill: Find every distinct set of four values in an array that adds up to a target sum — no value-quadruplet repeated, even when built from different positions.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An array of integers and a target sum arrive together, and the task is to surface every combination of four distinct positions whose values add up to that target.

As with its three-value cousin, what matters is the quadruplet of values, not the positions that produced them — the same four numbers found through different positions still counts as one answer.

Order within a quadruplet and order among the quadruplets returned doesn't affect correctness; only the distinct set of value-quadruplets matters.

EX 01
nums = [1, 0, -1, 0, -2, 2] · target = 0
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
MIX OF POSITIVES, NEGATIVES, AND DUPLICATE ZEROS
EX 02
nums = [2, 2, 2, 2, 2] · target = 8
[[2, 2, 2, 2]]
EVERY VALUE IDENTICAL, STILL ONE QUADRUPLET
EX 03
nums = [1, 2, 3, 4] · target = 10
[[1, 2, 3, 4]]
MINIMUM SIZE, USES EVERY ELEMENT
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Four nested loops check every quadruple directly, but that re-derives a smaller sum problem you already know how to solve fast. What does fixing two of the four values reduce this to?

HINT 2 THE STRUCTURE

Sort the array. Fix the first two values as anchors with nested loops, and the remaining two become a two-sum on a sorted suffix — closable with inward pointers.

HINT 3 ONE STEP FROM THE ANSWER

For each pair of anchors, walk lo from just past the second anchor and hi from the end: sum too small, push lo right; too big, pull hi left; equal, record the quadruplet and skip past duplicate values on both sides before continuing.

COACH'S BOARD — THE PATTERN, STEP BY STEP
TWO ANCHORS, TWO POINTERSPATTERN · SORT + TWO ANCHORSnums = [-2, -1, 0, 0, 1, 2] (sorted for the walk) · target = 0
-2
-1
0
0
1
2
STEP 1

Sorted: [-2, -1, 0, 0, 1, 2], target 0. Fix two anchors i and j, close the rest with two pointers.

STEP 1 / 10 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/4sum.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        out = []
        for i in range(n - 3):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            for j in range(i + 1, n - 2):
                if j > i + 1 and nums[j] == nums[j - 1]:
                    continue
                lo, hi = j + 1, n - 1
                while lo < hi:
                    s = nums[i] + nums[j] + nums[lo] + nums[hi]
                    if s < target:
                        lo += 1
                    elif s > target:
                        hi -= 1
                    else:
                        out.append([nums[i], nums[j], nums[lo], nums[hi]])
                        lo += 1
                        while lo < hi and nums[lo] == nums[lo - 1]:
                            lo += 1
                        hi -= 1
                        while lo < hi and nums[hi] == nums[hi + 1]:
                            hi -= 1
        return out
TIME O(N³)SPACE O(1)PYTHON · RACE PACE · 27 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED