Sliding Window
A window is a contiguous range [left, right] of an array or string. Instead of
re-examining every range from scratch (O(n²)), you slide it: extend right by one, and
move left forward only when the window breaks a rule. Each index enters and leaves the
window at most once, so the total work is O(n).
When to reach for it
Section titled “When to reach for it”- The problem asks about a contiguous subarray or substring.
- You want the longest, shortest, or best range satisfying a condition.
- The condition can be checked incrementally (a count, a sum, a set of seen characters).
- Brute force tries every start and end pair.
- Keywords: “substring”, “subarray”, “at most k”, “without repeating”, “contains all of”.
Template
Section titled “Template”left = 0state = {} # counts, sum, last-seen index: whatever the rule needsbest = 0for right, item in enumerate(items): add(state, item) # 1. grow: take in the new element while window_is_invalid(state): # 2. shrink until the rule holds again remove(state, items[left]) left += 1 best = max(best, right - left + 1) # 3. record (for "shortest", record inside a valid window)Longest-valid problems record after shrinking. Shortest-valid problems (like Minimum Window Substring) shrink while the window is still valid and record on each step.
Problems in this guide
Section titled “Problems in this guide”- Best Time to Buy and Sell Stock — track the cheapest day so far
- Longest Substring Without Repeating Characters — move left past the last duplicate
- Minimum Window Substring — need/have counts, shrink while still valid