SDE & MLE Prep

Sliding Window

When to use: contiguous subarray/substring with a constraint ("longest/shortest/count of windows such that …") where expanding/shrinking the window changes the constraint monotonically.

  • Variable window: grow r every step; while the window is invalid, shrink l. Answer is updated when valid.
  • Fixed window of size k: add a[r], remove a[r-k].
  • Needs non-negative numbers for sum constraints — with negatives use prefix sums (see 560).
l = 0
for r, x in enumerate(a):
    add(x)
    while invalid():
        remove(a[l]); l += 1
    best = max(best, r - l + 1)

Problems