Back to All Blogs1 min read10 Sept 2026
DSA Patterns That Actually Matter · Part 2 of 5
Sliding Window: Turn Repeated Range Work Into Linear Time
“Learn fixed and variable windows for subarrays and substrings.”
Sliding Window
Sliding window is useful for contiguous subarrays or substrings.
function maxWindowSum(nums: number[], k: 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];
sum -= nums[right - k];
best = Math.max(best, sum);
}
return best;
}
Variable Window
Expand right
↓
Window becomes valid
↓
Shrink left while possible
↓
Save answer
Common examples include longest substring without repeating characters and minimum-size subarray.
Note
Not every subarray problem is a sliding-window problem.
Finished this article?
Mark it done to update your series progress.