Skip to main content
Intermediate ~15 min read

Sliding Window

Turn "recompute every subarray" into a single O(n) pass by maintaining a window that grows and shrinks.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Big O Notation & Time Complexity

"Find the longest substring with at most K distinct characters." "Max sum of any 3 consecutive elements." These problems are about contiguous stretches of an array. The naive approach recomputes each stretch from scratch, O(n·k) or O(n²). The sliding window insight: when the window moves one step, most of it is unchanged, so update the state incrementally instead of recomputing.

There are two shapes. Fixed-size windows slide one position at a time: add the entering element, remove the leaving one, and the sum (or count) updates in O(1). Variable-size windows grow and shrink dynamically: expand the right edge to include elements while the condition holds, shrink the left edge when it breaks. Both shapes keep two pointers, and each element enters and leaves the window at most once, that's the O(n) proof.

Shape 1, fixed window: max sum of any k consecutive elements

sliding-window-fixed.js
function maxSumWindow(arr, k) {
  if (k > arr.length || k <= 0) return null;
  let windowSum = 0;
  for (let i = 0; i < k; i++) windowSum += arr[i];   // first window
  let best = windowSum;
  for (let i = k; i < arr.length; i++) {
    windowSum += arr[i] - arr[i - k];  // add entering, drop leaving, O(1)
    best = Math.max(best, windowSum);
  }
  return best;
}
// maxSumWindow([2, 1, 5, 1, 3, 2], 3) → 9  (window [5, 1, 3])

Shape 2, variable window: smallest subarray with sum ≥ target

sliding-window-variable.js
function smallestSubarrayWithSum(arr, target) {
  let left = 0, sum = 0, bestLen = Infinity;
  for (let right = 0; right < arr.length; right++) {
    sum += arr[right];                        // expand: absorb arr[right]
    while (sum >= target) {                   // condition met → try shrinking
      bestLen = Math.min(bestLen, right - left + 1);
      sum -= arr[left];                       // shrink from the left
      left++;
    }
  }
  return bestLen === Infinity ? 0 : bestLen;
}
// smallestSubarrayWithSum([2, 3, 1, 2, 4, 3], 7) → 2  ([4, 3])

Practice

arr = [1, 4, 2, 9], k = 2. What does the fixed-size window sum sequence look like, and which window wins?

Reveal explanation

Window sums are 5, 6, 11, so [2, 9] is the winning window with sum 11. Each next sum = previous + entering - leaving (e.g. 6 = 5 + 2 - 1).

Check your understanding

  1. 1.Why is the variable-window algorithm O(n) even though there's a while-loop inside a for-loop?
  2. 2.Which problem fits the sliding window pattern?
  3. 3.In the fixed-size window sum, why does windowSum += arr[i] - arr[i - k] keep the total correct?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going