Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Sliding window

A window that grows on the right, shrinks on the left, and holds an invariant at all times.


When it applies

t m m z u x t lo jumps past the repeat hi always moves right the window is valid at every step

Use a window when the answer is a contiguous run and there is a property that breaks as the run grows and can be repaired by dropping elements from the left. Because the left edge never moves backwards, the scan stays linear however often the window resizes.

Signals: "longest substring such that", "subarray with sum at most", "at most k distinct", "minimum window containing".


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

lo = 0
for hi, x in enumerate(a):
    add(x)                      # extend the window to the right
    while violates():           # repair it from the left
        remove(a[lo]); lo += 1
    best = max(best, hi - lo + 1)

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.