Data Structures & Algorithms / Module 5: Algorithm patterns
Topic 5.2
Sliding window
Moving a run of data forward and updating the result from its two ends only.
Watch: the window slides one step: one number comes in, one goes out. The total is updated without adding everything again.
- moving now
- passed / marked
- finished / the result
- no longer used
Like a train window
From a train window you can see four electricity poles at once. As the train moves, a new pole appears ahead and one disappears behind. You don't need to recount all four to know what's in view. Just note what came in and what went out.
A fixed-size window
The figure's example: the largest sum of 4 numbers in a row. Re-adding every window costs k additions per position, about n × k in total. Sliding costs one add and one subtract per position, about 2n in total. With k = 1,000 and a million values, that is 2 million steps, not a billion.
Code, for programmersLargest sum of k numbers in a row
function maxWindowSum(a, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += a[i]; // first window
let best = sum;
for (let i = k; i < a.length; i++) {
sum += a[i] - a[i - k]; // one in, one out
best = Math.max(best, sum);
}
return best;
}A window that grows and shrinks
The more common version: the window size isn't fixed. The right end keeps moving to take in elements; the left end moves when the window breaks a rule. Example: "the longest substring with no repeated letter".
Both ends only move forward, each at most n times, so the total is still O(n).
Code, for programmersLongest substring with no repeated letter
function longestUnique(s) {
const seen = new Set();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
while (seen.has(s[right])) seen.delete(s[left++]); // shrink until valid
seen.add(s[right]);
best = Math.max(best, right - left + 1);
}
return best;
}Quiz
A window of size k slides one position. How many elements change?
With a window that grows and shrinks, why is the total still O(n)?
Which feature fits a sliding window best?
0 of 3 answered.