Sliding Window
Solve subarray and substring problems in one pass by keeping a window of contiguous elements and updating it as it moves, instead of recomputing every range.
Overview
A window is a contiguous range of an array or string, marked by two indexes, left and right. Many problems ask about every contiguous range: the largest sum, the longest run with no repeats, the number of ranges that meet a rule. Checking each range from scratch repeats work, because neighboring ranges share almost all of their elements. The sliding window keeps a small summary of the current range (a sum, a count map, a set) and updates it when one element enters on the right or one leaves on the left. Each update costs O(1), so the whole scan costs O(n).
The saving is large. Take n = 100,000 elements and windows of size k = 1,000. Recomputing each window from scratch is O(n·k): there are n − k + 1 windows of k elements each, so (n − k + 1) · k = 99,001,000, about 99 million additions. Sliding is O(n): it builds the first window with k additions, then adds the new element and drops the old one at each move, so k + 2(n − k) = 199,000, about 199 thousand operations.
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
Fixed-size window
The rule: when the size k is given, build the first window, then move it one step at a time. Each step adds nums[i], subtracts nums[i - k], and checks the answer; nothing inside the window is summed again.
- Sum the first k elements.
- Add nums[i], the element entering.
- Subtract nums[i - k], the element leaving.
- Update the best answer, then move i on by one and repeat from step 2 while i < n.
The answer is 18, and each element was added once and subtracted at most once. The lab below runs this walk. Its other tabs, Longest, Shortest, Count ≤ K and Max (deque), trace the examples in the sections that follow.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio