Sliding window technique — how it solves substring/subarray problems
Maintain a window [l, r] over an array/string; expand by moving r, shrink by moving l when the window violates a constraint. Turns O(n²) brute force into O(n) for problems like 'longest substring without repeating chars', 'min window substring', and 'max sum of subarray of size k'.
Sliding window is a two-pointer pattern over contiguous subarrays/substrings that turns nested-loop O(n²) into single-pass O(n).
The pattern
Maintain a window [l, r] and a running state (sum, frequency map, char set). Expand by moving r forward; shrink from l when the window violates a constraint; record the best window as you go.
Two flavors
1. Fixed-size window — "max sum of subarray of size k"
function maxSum(arr, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += arr[i];
let best = sum;
for (let r = k; r < arr.length; r++) {
sum += arr[r] - arr[r - k]; // slide
best = Math.max(best, sum);
}
return best;
}2. Variable-size window — "longest substring without repeating chars"
function lengthOfLongestSubstring(s) {
const seen = new Map();
let l = 0, best = 0;
for (let r = 0; r < s.length; r++) {
if (seen.has(s[r]) && seen.get(s[r]) >= l) {
l = seen.get(s[r]) + 1; // shrink
}
seen.set(s[r], r);
best = Math.max(best, r - l + 1);
}
return best;
}When to reach for it
- Asks about contiguous subarrays/substrings (not subsequences).
- Asks for a max/min length or sum/count under a constraint.
- Constraint changes monotonically as the window grows (so shrinking restores validity).
Classic problems
- Longest substring without repeating characters.
- Minimum window substring (smallest window containing all chars of t).
- Max sum subarray of size k.
- Longest substring with at most k distinct characters.
- Find all anagrams of p in s.
Interview framing
"For contiguous-range problems with a constraint, I think sliding window: a left and right pointer, expand right to grow, shrink left when constrained, track the best window as I go. It collapses the obvious O(n²) of nested loops into O(n) with a single pass and a running state — usually a frequency map or running sum."
Follow-up questions
- •Walk through 'longest substring without repeating chars'.
- •When does sliding window NOT work — what constraint shape breaks it?
- •Fixed vs variable window — when do you use which?
Common mistakes
- •Trying to use it on non-contiguous (subsequence) problems.
- •Forgetting to update the running state when shrinking.
- •Off-by-one in window size (r - l vs r - l + 1).
Performance considerations
- •O(n) time with O(k) auxiliary space for the running state. Each element enters and leaves the window at most once → amortized O(1) per step.
Edge cases
- •Empty input.
- •All same characters.
- •Window size larger than input.
Real-world examples
- •Search-bar autocomplete that scores recent characters in a stream.
- •Rate limiting (count of requests in last N seconds).
- •Find-on-page substring matching.