~/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.

Sliding window

Sliding window

Grow right, shrink left while invalid; monotonic deque for window max/min.

Notes

Recognise it when: you want the longest or shortest contiguous subarray or substring that satisfies a condition that stays monotone as the window grows.

left = 0
for right, ch in enumerate(s):
    add(ch)
    while invalid():
        remove(s[left]); left += 1
    best = max(best, right - left + 1)
  • Minimum window: shrink while valid, recording the answer inside the loop.
  • Fixed size k: add a[r] and remove a[r - k].
  • Window max/min: a monotonic deque of indexes. Pop from the back while the new value is bigger, and pop from the front when the index leaves the window.

Gotchas: the condition must be monotone (for example, "at most K distinct" works; "exactly K" = atMost(K) - atMost(K-1)). With negative numbers, a sum window breaks, so use prefix sums instead.

13 problems

Interview roadmap

Sliding window Grow and shrink a window over a string or array.

esc