Arrays & Hashing · Pattern 11 of 26

Sliding window of a fixed size

A window of exactly k items slides one step at a time: add the item coming in, remove the item going out. Every window is updated in O(1) instead of recomputed.

3 variations · 11 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • "Subarray (or substring) of length k"
  • Averages, sums or counts over every window of size k
  • Anagrams or permutations of a fixed word inside a text

The template

Sliding Window · Fixed
int maxWindowSum(int[] nums, int k) {      // largest sum of any k consecutive values
    int sum = 0;
    for (int i = 0; i < k; i++) sum += nums[i];   // the first window
    int best = sum;
    for (int i = k; i < nums.length; i++) {
        sum += nums[i] - nums[i - k];             // add the new, drop the old
        best = Math.max(best, sum);
    }
    return best;
}

The variations

  1. 1Add the new, drop the old

    Keep a running sum or count for the window. "Take k cards from the ends" is the same as "leave a window of n − k in the middle".

  2. 2Count characters in the window

    Keep letter counts for the window and for the word you are looking for. When they match, the window is an anagram.

  3. 3A window of time or distance

    The window is "within k indexes" or "within one hour". Keep a set of what is inside, or sort times and compare item i with item i + 2.

Mistakes to avoid

  • Removing nums[i - k + 1] instead of nums[i - k] (off by one).
  • Comparing two 26-letter count arrays from scratch for every window: keep a "matches" counter instead, or accept the 26× constant.
  • Forgetting to check the very first window.
Next: Sliding window of a variable size →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.