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

3Sum

MEDIUM✓ CHIP-TIMEDLC #15 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Find every unique triple of values that sums to zero — value-triples, not index-triples, so the same numbers in a different order never count twice.

An array of integers arrives, and the task is to surface every combination of three distinct positions whose values add up to zero.

What matters is the triple of values, not which positions produced them — two triples with the same three numbers, even from different index combinations, count as one and only one answer.

The order of numbers within a triple, and the order triples appear in the result, doesn't matter for correctness; only the set of distinct value-triples found matters.

  • array length runs from zero up to a few thousand elements
  • values can be negative, zero, or positive, with duplicates common
  • each triple must use three different positions in the array
  • duplicate value-triples must be collapsed to one entry each
EX 01
nums = [-3, 1, 2, -2, 0, 3]
→ [[-3, 0, 3], [-3, 1, 2], [-2, 0, 2]]
EX 02
nums = [0, 0, 0]
→ [[0, 0, 0]]
EX 03
nums = [1, 2, 3]
→ []

The hintstake only what you need

HINT 1 THE NUDGE

Cubic tries every triple and then fights duplicates on top. Sorting first makes both problems easier at once.

HINT 2 THE STRUCTURE

Fix the smallest element of the triple; what remains is two-sum on a sorted array — two pointers walking inward.

HINT 3 ONE STEP FROM THE ANSWER

Skip equal neighbours when advancing the anchor AND after each found pair — that is where the dedup lives. Sum too small → left pointer right; too big → right pointer left.

Coach's boardthe pattern, step by step

ANCHOR AND CLOSEPATTERN · SORT + TWO POINTERSnums = [-4, -1, -1, 0, 1, 2] (sorted for the walk)
-4
-1
-1
0
1
2
STEP 1

Sorted the array: [-4, -1, -1, 0, 1, 2]. Fix the smallest value as anchor, close the rest with two pointers.

STEP 1 / 10 · ← → WORK TOO

The splitstwo paces, two languages

grind/3sum.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        out = []
        n = len(nums)
        for i in range(n - 2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            lo, hi = i + 1, n - 1
            while lo < hi:
                s = nums[i] + nums[lo] + nums[hi]
                if s < 0:
                    lo += 1
                elif s > 0:
                    hi -= 1
                else:
                    out.append([nums[i], nums[lo], nums[hi]])
                    lo += 1
                    while lo < hi and nums[lo] == nums[lo - 1]:
                        lo += 1
                    hi -= 1
        return out
TIME O(N²)SPACE O(1)PYTHON · RACE PACE · 22 LN

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