When is sliding window the right tool? Show the template.
Interviewers love sliding window because it turns O(n²) brute force into O(n). Recognizing when to apply it is the skill.
Use when: problem asks for a contiguous subarray/substring satisfying some property, and the property is monotonic under window expansion/contraction.
Fixed window (size k): advance right, when window exceeds k advance left by 1. Maintain aggregate.
Variable window: advance right unconditionally; while window invalid, advance left. Track best at valid windows.
Maintain aggregates incrementally — counter dict, sum, max in deque — so each step is O(1) amortized.
Classic problems: longest substring without repeat, min window substring, max sum subarray of size k, longest substring with at most k distinct.
I reach for sliding window when the question is "longest/smallest/best contiguous X such that..." and expanding the window monotonically changes validity. Template: two pointers l and r. Fixed-size: r++ each step, l++ when r-l+1>k. Variable: r++ unconditionally, while (invalid) l++. For 'longest substring without repeat' I keep a char-count map, expand r and increment, while any count>1 I advance l and decrement. Answer updates when the window is valid. For 'min window substring' I track how many required chars are still missing, shrink whenever missing==0. The trick is defining 'valid' as a monotonic predicate — if it's not monotonic, sliding window won't work and you probably need DP or hash+count.
Pair sliding window with a HashMap/counter for "distinct chars" style constraints.
Monotonic deque handles "max in window" in O(1) amortized — leetcode 239.
HireMe AI (即答侠) gives the two templates side-by-side with 6 worked examples — pattern recognition gets automatic.
Sliding window is a specific two-pointer flavor where both pointers only move forward. General two-pointer also includes opposite-end techniques (sorted-array sum).
Almost never in classic sliding window — if it does, you probably need DP or a different structure.
HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.
Try HireMe AI Free