Sliding Window: Fixed and variable sliding windows
Goal: Learn the pattern first, then apply it to the 7 roadmap problems in this chapter.
When this pattern appears
The question asks about a contiguous substring/subarray and a condition can be maintained as endpoints move.
The reusable idea
Expand to add information and shrink when invalid (or once valid for a minimum). Each endpoint moves forward at most n times.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
What makes a window valid, and what one update changes that validity?
Common failure modes
Window size, exact frequency equality, last-window checks, and stale frequency maxima.
Chapter problems from the workbook
- #16 · Best Time to Buy and Sell Stock — Day 9, Easy. Open problem ↗
- #17 · Longest Substring Without Repeating Characters — Day 9, Medium. Open problem ↗
- #18 · Longest Repeating Character Replacement — Day 10, Medium. Open problem ↗
- #19 · Permutation in String — Day 10, Medium. Open problem ↗
- #20 · Find All Anagrams in a String — Day 11, Medium. Open problem ↗
- #21 · Minimum Window Substring — Day 11, Hard. Open problem ↗
- #22 · Sliding Window Maximum — Day 12, Hard. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.