Sliding Window
A sliding window maintains a contiguous slice of an array or string while two indexes move forward. Each element enters and leaves the window at most once, so the pass is O(n).
Detailed Explanation
Many problems ask about a subarray or substring: longest without repeating characters, minimum window covering a set of letters, maximum sum of k adjacent items. The naive approach starts at every left and grows right, which is O(n^2). A sliding window reuses the previous slice.
You keep left and right. right advances every iteration and you add arr[right] into some state (a sum, a Map of counts, a Set). When the window becomes invalid, you advance left and undo those elements until it is valid again. Then you record an answer (max(len), min(right - left + 1)).
Fixed windows have constant length k. You prefill the first k items, then at each step add the new right and subtract the element that just left. Maximum sum of k is the textbook.
Variable windows grow and shrink. The state must support O(1) or O(alphabet) add/remove. A Map of character counts is typical. If add/remove is O(n), you have not improved on the nested loop.
The window is always a contiguous range. Subsequences that skip elements are a different technique (two pointers on a sort, DP, or a stack).
What it costs you: a stale state when you move left and forget to decrement a count, then delete the map key at 0 (or you leave a 0 in the map and size is wrong). Also, applying a window to a problem whose constraint is not about a contiguous slice.
Reach for a sliding window when the problem says subarray/substring and the constraint is monotonic: growing right only makes the window "worse" or "heavier" in one dimension, so left only moves forward. Reach for prefix sums when the question is "sum of i..j" many times. Reach for DP when the slice quality is not monotonic.
Code Examples
function maxSumOfK(arr, k) {
let sum = 0;
for (let i = 0; i < k; i += 1) sum += arr[i];
let best = sum;
for (let right = k; right < arr.length; right += 1) {
sum += arr[right] - arr[right - k];
if (sum > best) best = sum;
}
return best;
}
console.log(maxSumOfK([2, 1, 5, 1, 3, 2], 3)); // => 9function longestUnique(s) {
const last = new Map();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right += 1) {
const ch = s[right];
if (last.has(ch) && last.get(ch) >= left) {
left = last.get(ch) + 1;
}
last.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}
console.log(longestUnique("abba")); // => 2
console.log(longestUnique("abcabcbb")); // => 3Common Gotchas
Counts must be undone when `left` moves
a `Map` whose `size` includes zero-count keys will lie. `delete` when the count hits 0.
The window is contiguous
if the problem allows gaps, this is the wrong tool.
Fixed k needs `n >= k`
decide whether to throw or return 0 when the array is shorter than the window.
Character windows on UTF-16
indexes are code units. For emoji-heavy strings, iterate code points first.