Guided Lesson Notes
Understanding Sliding Window
Sliding window is a pattern for contiguous ranges in arrays and strings. Instead of rebuilding the answer for every possible subarray, the algorithm keeps one active window and updates a small amount of state as the window moves.
The reason this works is reuse. When the right edge moves forward by one item, the old window is almost the same as the new window. For a fixed-size window, one item enters and one item leaves. For a variable-size window, the right edge expands until the window becomes invalid, then the left edge shrinks until the invariant is restored.
The invariant is the heart of the pattern. In a maximum-sum length-k problem, the invariant might be: currentSum is exactly the sum of the last k elements. In a longest-substring problem, the invariant might be: every character count inside the current window stays within the allowed limit.
Sliding window is not a magic replacement for all nested loops. It usually needs a monotonic condition: after the right side expands, moving the left side forward should help repair the window. That is why nonnegative array sums work naturally, but arrays with negative numbers often need prefix sums, hash maps, or a deque instead.
Competitive programming problems often hide sliding window behind phrases like longest contiguous block, shortest subarray, at most k, no more than k distinct values, or every window of length k. The winning move is to define what enters, what leaves, and what state must be updated in O(1).
