Scanning & Windows
Sliding Window
🪟
Picture this
A massive pane of glass slides across the marble counter, framing exactly the dishes that matter right now.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
substringsubarraycontiguouslongestshortestat most kwindow
Ask yourself
- Is the answer a contiguous run (substring / subarray)?
- Are you asked for longest / shortest / count under a constraint?
- Can you expand right, then shrink left while invalid?
Canonical template
let left = 0;
for (let right = 0; right < a.length; right++) {
add(a[right]);
while (invalid()) remove(a[left++]);
best = Math.max(best, right - left + 1);
}
Common pitfalls
Shrinking with
ifinstead ofwhile.
Updating the answer before restoring validity.