Dynamic range tracking
Sliding Window
Two pointers stretch and shrink a window while maintaining running stats. Perfect when you must find the best contiguous subarray or substring under a constraint.
Imagine laying a picture frame over a long strip of numbers or letters and gently sliding it left and right. You only care about what sits inside the frame, so you keep tiny notes (such as the sum or which characters are present) and adjust the frame whenever the rules are broken. Because the frame never jumps backward, every element is touched a small number of times.
How to Spot This Pattern
- Sketch a small window over the input and ask: “Can my answer be expressed as elements that sit next to each other?” If yes, sliding the window is promising.
- Look for limits such as “at most k repeats”, “total must stay under budget”, or “must include every letter in the pattern”. These limits tell you when to widen or shrink the frame.
- Notice when the interviewer expects you to stream data or handle very long strings. Sliding windows shine because they examine each character once instead of restarting from scratch.
Algorithm Example
Longest Substring Without Repeating Characters
Keep a hash set for the current window; shrink from the left whenever you see a duplicate.
"Longest substring" plus "without repeating" screams sliding window with a set or frequency map.
O(n) time · O(min(n, alphabet)) space
Algorithm Example
Minimum Window Substring
Grow the window until you cover all targets, then shrink to find the tightest range.
Need smallest substring that covers a multiset of characters.
O(n) time · O(k) space (k distinct tracked chars)
Algorithm Example
Max Consecutive Ones III / Fixed Window
Maintain counts while sliding a fixed or almost fixed window when the question says "size k".
Fixed-length or streaming questions with running average/median style output.
O(n) time · O(1) extra space