~/problems

Problems

Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.

Two pointers

Two pointers

Sorted input + moving ends inward; skip duplicates; pairs and triples.

Notes

Recognise it when: the array is sorted (or you can sort it) and you want pairs or triples with a target sum, or you're partitioning or removing in place.

nums.sort()
for i in range(len(nums) - 2):
    if i and nums[i] == nums[i - 1]: continue
    lo, hi = i + 1, len(nums) - 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

Why it works: each move rules out a whole row or column of candidate pairs.

Container with most water: always move the shorter side.

14 problems

Interview roadmap

Two pointers Scan from both ends, or fast and slow.

esc