Sliding Window
Visualize 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.
Sliding Window: Max Sum Subarray
Calculate the maximum sum of any contiguous subarray of size k. Sliding window reduces repeated calculations.
Initialize variables: maxSum = 0, windowSum = 0
Initialize variables: maxSum = 0, windowSum = 0
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
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
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