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.
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
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;
} def max_window_sum(nums, k): # largest sum of any k consecutive values
s = sum(nums[:k]) # the first window
best = s
for i in range(k, len(nums)):
s += nums[i] - nums[i - k] # add the new, drop the old
best = max(best, s)
return best int maxWindowSum(vector<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 < (int)nums.size(); i++) {
sum += nums[i] - nums[i - k]; // add the new, drop the old
best = max(best, sum);
}
return best;
} function maxWindowSum(nums, k) { // largest sum of any k consecutive values
let sum = 0;
for (let i = 0; i < k; i++) sum += nums[i]; // the first window
let best = sum;
for (let 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
-
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".
Now you solve -
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.
Now you solve -
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.
Now you solve
Mistakes to avoid
- Removing
nums[i - k + 1]instead ofnums[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.
Lesson done
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.