Sliding window is a pattern for problems about continuous ranges inside an array or string.
Instead of recomputing a range again and again, the window moves one step at a time while reusing previous work.
Fixed-size window
Use this when the problem gives a size k.
Example: maximum sum of any subarray of length k.
function maxSumOfK(values, k) {
let windowSum = 0;
for (let i = 0; i < k; i++) {
windowSum += values[i];
}
let best = windowSum;
for (let right = k; right < values.length; right++) {
windowSum += values[right];
windowSum -= values[right - k];
best = Math.max(best, windowSum);
}
return best;
}
Variable-size window
Use this when the window expands and shrinks based on a condition.
Common examples include longest substring without repeating characters and smallest subarray with sum at least target.
Complexity
Most sliding window solutions are O(n) because each pointer moves forward at most n times.
Common signs
- subarray or substring
- contiguous range
- longest or shortest range
- fixed length
k - at most or at least condition
Practice problems
- Maximum sum of a subarray of size
k. - Average of every subarray of size
k. - Longest substring without repeating characters.
- Smallest subarray with sum at least target.
- Longest subarray with at most two distinct values.
Practice links
Interactive walkthrough
Sliding Window Visualizer
Move a continuous range without recomputing everything. Step 1 left
Step 2 sum
Step 3 right
Step 4 best