Lesson 125 of 296
Sliding window: fixed size
What you will learn
- What a sliding window is
- Fixed-size windows
- Maximum sum of k consecutive items
- Find All Anagrams in a String
On this page
The idea
Many problems ask about contiguous parts of an array or string: subarrays or substrings. A window is a range [left, right]. Instead of recalculating everything for each new range, slide the window: add the item coming in on the right, remove the item going out on the left.
This turns O(n × k) work into O(n).
Maximum sum of k consecutive numbers
nums = [2, 1, 5, 1, 3, 2], k = 3 → 9 (5 + 1 + 3).
Brute force: sum every window of 3 from scratch: O(n × k).
Sliding: the next window's sum = previous sum + new item − item that left.
function maxSumOfK(nums: number[], k: number): number {
if (k <= 0 || k > nums.length) return 0;
let windowSum = 0;
for (let i = 0; i < k; i++) windowSum += nums[i]!;
let best = windowSum;
for (let right = k; right < nums.length; right++) {
windowSum += nums[right]! - nums[right - k]!;
best = Math.max(best, windowSum);
}
return best;
}| Window | Sum |
|---|---|
| [2, 1, 5] | 8 |
| [1, 5, 1] | 8 − 2 + 1 = 7 |
| [5, 1, 3] | 7 − 1 + 3 = 9 |
| [1, 3, 2] | 9 − 5 + 2 = 6 |
O(n) time, O(1) space.
Find All Anagrams in a String
Problem (LeetCode 438): find all start indexes in s where a substring is an anagram of p.s = "cbaebabacd", p = "abc" → [0, 6].
Idea: every anagram of p has length p.length, so use a fixed window of that size, and keep letter counts for the window (Lesson 120). Compare with p's counts.
function findAnagrams(s: string, p: string): number[] {
const result: number[] = [];
if (p.length > s.length) return result;
const need = new Array<number>(26).fill(0);
const window = new Array<number>(26).fill(0);
const code = (ch: string) => ch.charCodeAt(0) - 97;
for (const ch of p) need[code(ch)]!++;
for (let right = 0; right < s.length; right++) {
window[code(s[right]!)]!++;
if (right >= p.length) {
window[code(s[right - p.length]!)]!--;
}
if (right >= p.length - 1 && window.every((count, i) => count === need[i])) {
result.push(right - p.length + 1);
}
}
return result;
}Comparing two arrays of 26 is constant work, so the total is O(n) time, O(1) space. (A faster version keeps a count of how many letters currently match instead of comparing all 26.)
Recognising a fixed window
- "subarray / substring of length k"
- "every k consecutive items"
- The window size is given or fixed by the input (like
p.length).
How to say it in an interview
"For contiguous ranges of a fixed size k, I keep a running value for the current window and slide it one step at a time, adding the element entering on the right and removing the one leaving on the left. That turns an O(n times k) brute force into O(n). For Find All Anagrams I slide a window of length p with a 26-letter count array and compare it with p's counts at each position."
Key words
| Word | Meaning |
|---|---|
| Contiguous | Next to each other with no gaps |
| Subarray / substring | A contiguous part of an array / string |
| Sliding window | A range that moves along the data |
| Fixed window | A window whose size never changes |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.