Sliding window
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Maintain a window over a contiguous range while expanding and shrinking it.
- Choose fixed-size or variable-size windows for a problem.
- Track window state so each element enters and leaves the window once.
Overview
#Windows over contiguous ranges
A sliding window is two pointers that bound a contiguous range. You expand the right edge to include new elements and shrink the left edge to restore a condition. Because each index enters and leaves at most once, the total work is O(n).
Fixed-size window
Find the maximum sum of any k consecutive elements:
function maxWindowSum(values, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += values[i];
let best = sum;
for (let i = k; i < values.length; i++) {
sum += values[i] - values[i - k];
if (sum > best) best = sum;
}
return best;
}
The window size stays k. Add the entering element and subtract the leaving one.
Variable-size window
Find the length of the longest substring without repeating characters:
function longestUnique(s) {
const seen = new Map();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (seen.has(ch) && seen.get(ch) >= left) left = seen.get(ch) + 1;
seen.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
When a repeat appears inside the window, jump left past the previous occurrence. The window never needs to shrink one step at a time here, but the state stays consistent.
Choosing the window type
Use a fixed window when the problem names a size k. Use a variable window when the problem asks for the longest or shortest range satisfying a condition. Either way, define exactly what the window state means (a sum, a count map, a frequency array) before writing the loop.
Practice next
- Find the smallest window containing all characters of a target string.
- Maintain the maximum of each fixed window using a monotonic deque.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
For values [2, 1, 5, 1, 3, 2] and k = 3, what is the maximum window sum?
starter.javascript// window sums: [2,1,5], [1,5,1], [5,1,3], [1,3,2]Reveal the reference answer
reference.javascriptThe window sums are 8, 7, 9 and 6. The maximum is 9 from [5, 1, 3].Authored expected output: 9
The fixed window slides one step at a time, adding the entering value and subtracting the leaving one.
Exercise 2Predict
What is the length of the longest substring without repeating characters in 'abcabcbb'?
starter.javascript// trace left and right over the stringReveal the reference answer
reference.javascriptThe window 'abc' has length 3. When the second 'a' appears, left jumps to index 1, and the window stays length 3. No longer window exists, so the answer is 3.Authored expected output: 3
The window grows and jumps left past repeats, never exceeding length 3.
Exercise 3Debug
This fixed-window maximum-sum function works for valid window sizes but returns a wrong answer for invalid ones. Find the missing guard and name the k values that break it.
starter.javascriptfunction maxWindowSum(values, k) { let sum = 0; for (let i = 0; i < k; i++) sum += values[i]; let best = sum; for (let i = k; i < values.length; i++) { sum += values[i] - values[i - k]; best = Math.max(best, sum); } return best; }Reveal the reference answer
reference.javascriptfunction maxWindowSum(values, k) { if (k <= 0 || k > values.length) return null; let sum = 0; for (let i = 0; i < k; i++) sum += values[i]; let best = sum; for (let i = k; i < values.length; i++) { sum += values[i] - values[i - k]; if (sum > best) best = sum; } return best; }Authored expected output: Guard k <= 0 and k > values.length before summing
With k greater than the array length the initial loop reads undefined and the sum becomes NaN. With k of zero the window is empty and the function returns 0, which is not a valid maximum. Guarding the invalid sizes prevents silent wrong answers.
Common misconceptions
#- A sliding window is always a fixed size. Variable-size windows are common and often the point.
- You can shrink the window by one step in a loop and still call it O(n). Shrinking one step at a time is fine as long as left never moves back, because total movement is bounded by n.
- The window state updates itself. You must add the entering element and remove the leaving element explicitly.
Follow-up practice
#- dsa-from-zero-strings-and-hashing
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.