core pattern
Sliding Window
Maintain a dynamic window over contiguous elements to efficiently compute aggregates like sum, max, or count. Expand the window by adding elements, shrink by removing.
Time
O(n)
Space
O(1)
🧠Mental Model
“A spotlight sliding across a stage — it illuminates a section at a time while moving forward.”
Verbal cue: Expand right edge, shrink left edge when condition breaks
🎯Recognition Triggers
When you see these patterns in a problem, consider this approach:
Subarray or substringContiguous elementsMaximum/minimum of size KLongest/shortest with conditionWindow with specific sumString permutation/anagram
💡Interview Tips
- 1Clarify if the window size is fixed or dynamic
- 2For variable windows, define the shrinking condition clearly
- 3Use a hash map when tracking character frequencies
- 4Consider what state you need to maintain in the window
⚠️Common Mistakes
- ✕Not tracking when to shrink the window properly
- ✕Forgetting to update the answer before shrinking
- ✕Using wrong window size calculation (right - left + 1)
- ✕Not handling edge cases: empty array, k > array length