Sliding Window
Example
let best = -Infinity;
for (let i = 0; i + k <= nums.length; i++) {
const sum = nums.slice(i, i + k).reduce((a, b) => a + b, 0);
best = Math.max(best, sum);
}let sum = 0, best = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
if (i >= k) sum -= nums[i - k];
if (i >= k - 1) best = Math.max(best, sum);
}Adding the new element and subtracting the one that left makes each step O(1), so the whole scan is O(n).
Common mistakes
- Recomputing each window with
slice()andreduce(), turning O(n) into O(n·k). - Off-by-one window size from using
right - leftinstead ofright - left + 1.
Key points
- The window updates its running sum or counts as it moves, instead of re-summing every window in O(n·k).
- Character counts inside the window live in a
Mapor fixed-size array, not in repeatedincludes()scans. - A variable window shrinks from the left in a
whileloop until the constraint holds again.
Interview questions
Fixed vs variable sliding window: what is the difference?
A fixed window keeps size k, as in the max sum of k items. A variable window grows and shrinks to meet a condition, as in the longest substring without repeats.
What is the time complexity of a sliding window?
Usually O(n): each element enters the window once and leaves at most once, even with a nested while loop that shrinks it.
Does a sliding window work with negative numbers?
Fixed-size windows do. A variable window that shrinks when the sum is too large needs non-negative values; with negatives, use prefix sums and a hash map.
