Sliding Window
Software Engineer path · lesson 42 of 99Visualize the fixed-size Sliding Window technique for maximum-sum subarray problems. See how reusing the previous window sum avoids redundant calculation, reducing the O(n·k) nested-loop approach to a single O(n) pass.
Up to 14 whole numbers from -99 to 99.
Each slide costs one add and one subtract, whatever k is. Watch the operation total stay ≈ 2n.
Build the first window: add a[0] = 2 → sum 2.
- 1window = sum(a[0..k-1]); best = window
- 2for i in k .. n-1:
- 3 window += a[i] - a[i-k] # slide by one
- 4 best = max(best, window)
- 5return best
- Additions
- 1 / 8
- Subtractions
- 0 / 5
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Maximum sum of k elements
Order the fixed-size sliding window algorithm.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
What is the main benefit of Sliding Window over a naive nested loop?
Write the code
Max Sum Subarray of Size K
function maxSubarraySum(arr, k) {
// Your code here
}The short version
Think of taking a panoramic photo. Your camera can only see a small slice of the landscape at a time. You smoothly slide the camera (window) to the right to capture the next section without losing context.
In more depth
Sliding Window
Many array and string problems ask for the best — or the count — of something over every contiguous block of the input. Recomputing each block from scratch costs O(n·k) and is almost entirely wasted work, because consecutive blocks overlap in all but two elements.
The idea
Keep a window over the array and maintain its answer incrementally. Moving the window one step to the right adds one element on the right and removes one on the left, so a running sum, maximum or frequency count updates in O(1) rather than being rebuilt.
Two forms
Recognising it
The problem says contiguous subarray or substring and asks for a maximum, a minimum, a count, or the longest/shortest block satisfying some property. If the answer for a block can be updated cheaply when one element enters and one leaves, this is the pattern.
When to reach for this
- Find the **Longest/Shortest** substring/subarray with a condition
- Find a window of size K with max/min sum
- Contiguous section of data
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required