Sliding Window Pattern
Solve contiguous subarray and substring problems in O(n) by expanding a right pointer and shrinking a left pointer.
What you'll learn
- Recognize contiguous subarray/substring clues that call for Sliding Window
- Maintain a running window sum or character frequency map in O(n) total time
- Shrink the left pointer cleanly whenever the window violates a constraint
Whenever a problem asks for the longest/shortest/maximum contiguous subarray or substring, avoid recomputing each window from scratch in $O(n^2)$. A Sliding Window moves right forward to add an element and left forward to remove an element, visiting each item at most twice -> $O(n)$ time.
Fill-in-the-Blank Exercise
Fixed-Size Sliding Window
Update the running window sum by adding nums[i] and subtracting the outgoing element.
windowSum += nums[i] - nums[i - ];
best = Math.(best, windowSum);Live DSA Playground
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. Why does a variable-size Sliding Window with an inner while-loop still run in O(n) total time?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.