The Sliding Window pattern reduces nested loop algorithms from O(N²) down to O(N) by maintaining a contiguous subarray window defined by start/end pointers.
Sum first K elements [2, 1, 5] -> Window Sum = 8, Max Sum = 8.
Window [2, 1, 5] -> Sum = 8 -> Max = 8Slide window to [1, 5, 1]. New Sum = 8 - 2 + 1 = 7. Max Sum remains 8.
Window [1, 5, 1] -> Sum = 7 -> Max = 8Slide window to [5, 1, 3]. New Sum = 7 - 1 + 3 = 9. Max Sum updated to 9!
Window [5, 1, 3] -> Sum = 9 -> Max = 9A camera window slides along a moving train track. As a new car enters the right side of the window, the oldest car exits on the left.
500 steps (Linear)
O(N) Linear Time
O(1) / O(N) Space
Memory growth rate as N expands.
Relative efficiency rating for large N.
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Sliding Window Execution | O(N) | O(1) |
function maxSubarraySum(arr, k) {
let maxSum = 0, windowSum = 0;
for (let i = 0; i < k; i++) windowSum += arr[i];
maxSum = windowSum;
for (let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}Measures packet throughput inside rolling 5-second windows.
Computes 50-day moving average prices efficiently.
Validate your conceptual understanding, operation mechanics, and core concepts of Sliding Window.
Whenever a problem asks for maximum/minimum contiguous subarray or substring matching a condition, consider the Sliding Window pattern first!
Array loaded. Set window size K and click Slide Window to visualize window traversal.