Command Palette

Search for a command to run...

Module 7

Sliding Window

Keep a window over a contiguous range and update it as it moves, adding what enters and removing what leaves, instead of recomputing from scratch.

Intermediate 4 lessons 7 problems ~55 min of lessons

Sliding window is two pointers specialised for contiguous ranges. The right pointer grows the window, the left pointer shrinks it, and a small summary (a sum, a count map) is updated in O(1) per move. Every element enters once and leaves once, so the whole scan is O(n).

There are two shapes. Fixed windows keep exactly k elements. Variable windows grow until a rule breaks, then shrink until it holds again; they answer "longest" and "shortest" questions. The module finishes with the "at most K" trick that turns "exactly K" into two easier windows.

Best after: Two Pointers, Hashing

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The fixed window template: add the entering element, subtract the leaving one.

  2. The variable window for "longest": grow right, and when a character repeats, jump left past its previous position.

  3. The "shortest" variant: shrink while the window is valid, recording its length each time.

  4. A window is valid when (length − count of its most common letter) ≤ k; the max count never needs to decrease.

  5. A fixed window the size of the pattern, compared by letter counts: anagram search in O(n).

  6. The full shortest-window machine: need counts, a satisfied counter, grow until valid, shrink while valid.

  7. Count "exactly K" as atMost(K) − atMost(K − 1), where each at-most count is a simple window.