"Find the longest substring with at most K distinct characters." "Max sum of any 3 consecutive elements." These problems are about contiguous stretches of an array. The naive approach recomputes each stretch from scratch, O(n·k) or O(n²). The sliding window insight: when the window moves one step, most of it is unchanged, so update the state incrementally instead of recomputing.
There are two shapes. Fixed-size windows slide one position at a time: add the entering element, remove the leaving one, and the sum (or count) updates in O(1). Variable-size windows grow and shrink dynamically: expand the right edge to include elements while the condition holds, shrink the left edge when it breaks. Both shapes keep two pointers, and each element enters and leaves the window at most once, that's the O(n) proof.
Shape 1, fixed window: max sum of any k consecutive elements
function maxSumWindow(arr, k) {
if (k > arr.length || k <= 0) return null;
let windowSum = 0;
for (let i = 0; i < k; i++) windowSum += arr[i]; // first window
let best = windowSum;
for (let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k]; // add entering, drop leaving, O(1)
best = Math.max(best, windowSum);
}
return best;
}
// maxSumWindow([2, 1, 5, 1, 3, 2], 3) → 9 (window [5, 1, 3])Shape 2, variable window: smallest subarray with sum ≥ target
function smallestSubarrayWithSum(arr, target) {
let left = 0, sum = 0, bestLen = Infinity;
for (let right = 0; right < arr.length; right++) {
sum += arr[right]; // expand: absorb arr[right]
while (sum >= target) { // condition met → try shrinking
bestLen = Math.min(bestLen, right - left + 1);
sum -= arr[left]; // shrink from the left
left++;
}
}
return bestLen === Infinity ? 0 : bestLen;
}
// smallestSubarrayWithSum([2, 3, 1, 2, 4, 3], 7) → 2 ([4, 3])Practice
arr = [1, 4, 2, 9], k = 2. What does the fixed-size window sum sequence look like, and which window wins?
Reveal explanation
Window sums are 5, 6, 11, so [2, 9] is the winning window with sum 11. Each next sum = previous + entering - leaving (e.g. 6 = 5 + 2 - 1).