The home where you level up

Save my spot

Sliding Window

Term side of the Card.
Topic: Various
Unit title: Sliding Window
Categories: Technique
Explanation side of the Card

Explanation: The technique that moves a fixed or variable-size window across an array or string, updating the result incrementally instead of recomputing it. Ideal for problems involving sums, maximums or substrings within ranges.

Example

Wrongjs
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);
}
Rightjs
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() and reduce(), turning O(n) into O(n·k).
  • Off-by-one window size from using right - left instead of right - 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 Map or fixed-size array, not in repeated includes() scans.
  • A variable window shrinks from the left in a while loop 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.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy