Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Two Pointers

4Sum

MEDIUM✓ CHIP-TIMEDLC #18 — FULL STATEMENT

The briefingthe full drill, in my own words

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.

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.

  • array length runs up to a couple hundred elements
  • values and the target can be negative, zero, or positive
  • each quadruplet must use four distinct positions in the array
  • duplicate value-quadruplets must be collapsed to one entry each
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 hintstake 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 boardthe 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 splitstwo paces, two languages

grind/4sum.py — RACE 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-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED