Lesson 28
Sliding Window
Reuse the work from the last window instead of recomputing the next one.
01Why it matters & the intuition
Any question about the best contiguous subarray or substring — longest, shortest, max sum, at most k distinct — is usually a sliding window. It is one of the highest-yield interview patterns.
Think of it like…
A train window: as the train moves one metre, one metre of view appears on the right and one disappears on the left. You don't re-look at the whole view — you just update for what entered and what left.
02See it move
Press play, then step through slowly. Change the input and predict the next frame before you click.
- window
- repeat
- best
03Key ideas
Fixed-size window
Add the entering element, subtract the leaving element. Max sum of any k consecutive items becomes O(n).
Variable-size window
Expand right every step; shrink left while the window breaks the rule. Track the best valid window.
Window state
Keep what you need to test validity in O(1): a running sum, a character count map, or a set.
04Build it from scratch
A clean reference implementation. Read it line by line — then close it and write your own in the lab below.
function maxSumOfK(nums: number[], k: number): number {
let sum = 0;
for (let i = 0; i < k; i++) sum += nums[i];
let best = sum;
for (let right = k; right < nums.length; right++) {
sum += nums[right] - nums[right - k]; // slide
best = Math.max(best, sum);
}
return best;
}
function longestUniqueSubstring(s: string): number {
const lastSeen = new Map<string, number>();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
const prev = lastSeen.get(s[right]);
if (prev !== undefined && prev >= left) left = prev + 1; // shrink past the repeat
lastSeen.set(s[right], right);
best = Math.max(best, right - left + 1);
}
return best;
}05Complexity
| Operation | Time | Space |
|---|---|---|
| Fixed or variable window | O(n) | O(k) for window state |
| Brute force over all subarrays | O(n²) or worse | — |
06Check your understanding
07Code lab
Write Python(or switch to JavaScript) and run it against real test cases. Python runs inside your browser — nothing is uploaded — and a C++ reference solution is under “Solution”.
Longest substring without repeats
Write length_of_longest_substring(s) returning the length of the longest substring with no repeated characters.