Pattern #01
Sliding Window
EssentialLongest, shortest, or valid contiguous ranges over arrays and strings.
When to use
Use when the problem asks for a longest, shortest, or valid contiguous subarray/substring. never when order can be rearranged freely.
Recognition cues
- Contiguous subarray or substring
- Longest / shortest / at most K / exactly K
- Expand right, shrink left while maintaining a window invariant
Common pitfalls
- Off-by-one when updating best length (right - left + 1)
- Forgetting to update the map/counter when shrinking
- Using sliding window when indices need not be contiguous
90-second recognition drill
Which pattern fits best?
- Contiguous subarray or substring
- Longest / shortest / at most K / exactly K
- Expand right, shrink left while maintaining a window invariant
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
best = 0
How to think about it
Keep a window [left, right] over the sequence. Expand right one step at a time. A longest-window problem shrinks while the window is invalid. A shortest-window problem shrinks while it is still valid, and records the length only then. A fixed window moves both ends by the same width. The animation above is the skeleton: grow, fix, record. The catalog problems differ in what “fix” means, including one that jumps left instead of stepping it.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| No repeat | If last[ch] >= left, jump left to last[ch] + 1. The answer is the largest right - left + 1 |
LC 3 |
| Covering minimum | missing is how many distinct characters of t are still short. While missing == 0, record a strictly shorter span, then drop the left character. Empty t, or no cover, returns "" |
LC 76 |
| Positive sum minimum | Add nums[right]. While s >= target, record the length and drop nums[left]. No such window returns 0 |
LC 209 |
| Replacement budget | maxFreq only rises. While right - left + 1 - maxFreq > k, drop the left character. Equality with k stays |
LC 424 |
| Fixed permutation | The window width is len(s1). Two 26-slot counts must match, duplicates included. Each slide adds the new character and drops the one len(s1) behind. len(s1) > len(s2) is false |
LC 567 |
| At most two types | While the map has more than two keys, drop the left fruit and delete a key whose count hits 0. The answer is the largest right - left + 1 |
LC 904 |
Complexity baseline
Each index enters once, so these are O(n) time. LC 424 and LC 567 use a fixed 26-slot count, O(1) extra space. LC 3 and LC 76 keep a map of characters. LC 904 keeps a map of fruit types. LC 209 keeps a running sum.
From template to problem
- LC 3 stores the previous index of each character.
leftjumps when that index is still inside (last[ch] >= left). It does not shrink one step at a time. - LC 76 shrinks while
missing == 0.missingstarts as the number of distinct characters int, notlen(t). A needed character whose count falls below its requirement raisesmissing. - LC 209 shrinks while
s >= target. Every value is positive, so once a window fits, a longer one is not a new minimum. - LC 424 does not lower
maxFreqwhen the left character leaves. Shrink only whileright - left + 1 - maxFreq > k. - LC 567 compares two count arrays of width 26. The window width stays
len(s1). - LC 904 shrinks while a third key is present, and removes that key when its count hits 0.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
/**
* Sliding window (variable length), longest valid window.
* Expand `right`, shrink `left` while the invariant breaks, then record the answer.
*
* Minimum covering window: shrink while still valid, update `best` only when valid
* (often start with `best = Infinity`).
*/
function slidingWindow(s: string): number {
const freq = new Map<string, number>();
let left = 0;
let best = 0;
const windowOk = () => {
// Replace with the problem invariant (e.g. all unique, sum ≤ k).
return true;
};
for (let right = 0; right < s.length; right++) {
// 1) expand: add s[right] into window state
const add = s[right]!;
freq.set(add, (freq.get(add) ?? 0) + 1);
// 2) shrink while the invariant is broken
while (left <= right && !windowOk()) {
const rem = s[left]!;
const next = (freq.get(rem) ?? 0) - 1;
if (next <= 0) freq.delete(rem);
else freq.set(rem, next);
left++;
}
// 3) window [left, right] is valid, update answer
best = Math.max(best, right - left + 1);
}
return best;
}
export { slidingWindow };
/**
* Sliding window (variable length), longest valid window.
* Expand `right`, shrink `left` while the invariant breaks, then record the answer.
*
* Minimum covering window: shrink while still valid, update `best` only when valid
* (often start with `best = Infinity`).
*/
function slidingWindow(s: string): number {
const freq = new Map<string, number>();
let left = 0;
let best = 0;
const windowOk = () => {
// Replace with the problem invariant (e.g. all unique, sum ≤ k).
return true;
};
for (let right = 0; right < s.length; right++) {
// 1) expand: add s[right] into window state
const add = s[right]!;
freq.set(add, (freq.get(add) ?? 0) + 1);
// 2) shrink while the invariant is broken
while (left <= right && !windowOk()) {
const rem = s[left]!;
const next = (freq.get(rem) ?? 0) - 1;
if (next <= 0) freq.delete(rem);
else freq.set(rem, next);
left++;
}
// 3) window [left, right] is valid, update answer
best = Math.max(best, right - left + 1);
}
return best;
}
export { slidingWindow };
- 1#3 Longest Substring Without Repeating CharactersGuidemedium
- 2#76 Minimum Window SubstringGuidehard
- 3#209 Minimum Size Subarray SumGuidemedium
- 4#424 Longest Repeating Character ReplacementGuidemedium
- 5#567 Permutation in StringGuidemedium
- 6#904 Fruit Into BasketsGuidemedium