Sliding Window — the shape behind dozens of interview problems.
TL;DR
Maintain a contiguous range and slide its boundaries to avoid recomputation. Time O(n), space O(1) or O(k) for a frequency map.
When to reach for Sliding Window
- Contiguous subarray or substring constraint.
- You can move one boundary based on a monotone condition.
- Brute force is O(n·k) or O(n²).
Scenario variants (legal, original)
- Pharmacy Pickup — longest window with ≤ k distinct items.
- Rolling Peak Sensor — max in every window of size k.
- Unique DNA Run — longest substring with no repeated character.
Sliding Window in Python
def longest_unique(s: str) -> int:
seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1
seen[ch] = right
best = max(best, right - left + 1)
return bestSee language-specific tabs at /languages/python/patterns and the SQL variant at /languages/sql/patterns.
Common bugs
- Shrinking when you should extend first (window can miss candidates).
- Forgetting to update the answer after every right-move, not just after shrinks.
- Using < vs <= on the window condition — off-by-one on equality.
Related patterns
Frequently asked questions
- What is the sliding window pattern?
- Sliding Window is maintain a contiguous range and slide its boundaries to avoid recomputation. Time O(n), space O(1) or O(k) for a frequency map.
- When should I use sliding window?
- Use it when: Contiguous subarray or substring constraint. You can move one boundary based on a monotone condition. Brute force is O(n·k) or O(n²).
- What are the most common sliding window bugs?
- Shrinking when you should extend first (window can miss candidates). Forgetting to update the answer after every right-move, not just after shrinks. Using < vs <= on the window condition — off-by-one on equality.
- What problems use the sliding window pattern?
- Representative scenarios: Pharmacy Pickup — longest window with ≤ k distinct items. Rolling Peak Sensor — max in every window of size k. Unique DNA Run — longest substring with no repeated character.
- Is sliding window on the Blind 75?
- Yes — Sliding Window is one of the core patterns behind the Blind 75 list. See /blind-75 for the complete mapping.
Run the free diagnostic.
Ten-minute patterns quiz. No card. Personalized loop starts on the other side.