Linear patterns · mid
Sliding window
A sliding window keeps a range [left, right] and updates its state as right grows and left shrinks, so problems about the best contiguous substring or subarray run in O(n) instead of checking every range.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Fixed size k: add the new element, remove the one leaving (sum = sum + a[i] - a[i - k]).
- Variable size: expand right every step; while the window is invalid, shrink left; record the answer when it is valid.
- State is usually a hash map or a count array plus a counter (for example the number of 'missing' characters in minimum window substring).
- Longest substring without repeats: store the last index of each character; left = max(left, last[ch] + 1). The max matters ('abba').
- Sliding window maximum: a deque of indices with decreasing values gives O(n) (Java ArrayDeque, Python collections.deque, C++ std::deque); a heap gives O(n log n).
- It works for sums only when all numbers are non-negative; with negatives use prefix sums and a hash map.
The red pen
Common traps: mistake → fix
Mistake: Recompute the window from scratch each step
Fix: that is O(n·k); update it step by step.
Mistake: left = last[ch] + 1 is enough
Fix: left must never move backwards: use max.
Mistake: Sliding window works for 'sum equals k' with negative numbers
Fix: it does not; the shrink step cannot be decided.
Easy to hard
Questions interviewers ask, easy to hard
- Longest substring without repeating characters.
- Maximum sum of any window of size k.
- Minimum window substring that contains all characters of t (with repeats).
- Maximum of every window of size k in O(n).
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.