Sliding Window Technique
Table of Contents + β
Say someone gives you an array. They ask for the biggest sum you can get from any 3 numbers sitting next to each other. The simple idea is to add up every group of 3 and pick the best one. That works. But it does a lot of repeated adding. On a big array it gets slow. The sliding window technique fixes exactly that. It reuses the work you already did instead of adding the same numbers again and again.
π What Is a Sliding Window?
A sliding window is just a range of elements you look at together. Think of a small frame placed on top of the array. You keep a sum (or a count) for what sits inside that frame.
Now picture a real window on a train. As the train moves, the view shifts. One new tree comes into view on one side. One old tree leaves the view on the other side. You donβt look at the whole landscape again. You only notice what entered and what left.
The sliding window does the same thing with an array. When the frame moves one step to the right:
- one new element comes in on the right
- one old element goes out on the left
- you add the new one and subtract the old one
So you never rebuild the whole sum. You just adjust it.
π― The Problem It Solves
Letβs name the pain first. Say the array is [2, 1, 5, 1, 3, 2] and k = 3. You want the maximum sum of any 3 elements in a row.
The simple approach loops over every starting point. Then it adds k elements each time. That is k additions for every window. If the array has n elements, you get about n windows. Each one costs k work. So the total is O(n*k). When k is large this is slow. You keep adding the same middle elements over and over.
The sliding window does the adding only once. After the first window, every move is just one add and one subtract. That makes the whole thing run in O(n).
Note
A fixed window means the frame size never changes, like our k = 3. A variable window means the frame grows and shrinks based on a condition. For example βthe longest run whose sum stays under 100β. Today we focus on the fixed window. The idea of reusing work is the same in both.
πͺ Steps to Find the Maximum Sum Subarray of Size k
Here is the plan in plain steps. We build one starting window first, then we slide. Follow this order in the code.
- Add up the first k elements. Call this
windowSum. - Save it as your
maxSumso far. - Now slide. Move from index k to the end of the array.
- At each step, add the new element coming in (
arr[i]) and subtract the element leaving (arr[i - k]). - Compare this new
windowSumwithmaxSum. Keep the bigger one. - After the loop ends,
maxSumholds the answer.
The trick is in step 4. That one add and one subtract replaces a whole fresh loop.
π» The Code in 5 Languages
We run it on [2, 1, 5, 1, 3, 2] with k = 3. The best window is [5, 1, 3], which sums to 9.
def max_sum_window(arr, k): # Step 1: sum of the first window window_sum = sum(arr[:k])
# Step 2: that first sum is our best so far max_sum = window_sum
# Step 3-5: slide the window across the rest for i in range(k, len(arr)): window_sum += arr[i] - arr[i - k] # add new, drop old max_sum = max(max_sum, window_sum)
return max_sum
arr = [2, 1, 5, 1, 3, 2]k = 3print(f"Maximum sum of size {k}: {max_sum_window(arr, k)}")The output of the above code will be:
Maximum sum of size 3: 9Tip
The whole speed-up lives in this one line: windowSum += arr[i] - arr[i - k]. It adds the element entering the window and removes the element leaving it, in a single step. No inner loop needed.
π Watching the Window Move
Letβs trace it on [2, 1, 5, 1, 3, 2] with k = 3. This way you can see what happens at each slide.
Here is the same trace as a table. Notice we never re-add the full window. We only adjust by the element entering and the element leaving.
| Window | Element In | Element Out | Window Sum |
|---|---|---|---|
| [2, 1, 5] | first window | β | 8 |
| [1, 5, 1] | 1 | 2 | 7 |
| [5, 1, 3] | 3 | 1 | 9 |
| [1, 3, 2] | 2 | 5 | 6 |
The biggest sum we saw was 9, from the window [5, 1, 3]. Thatβs the answer.
β±οΈ Time and Space Complexity
The first loop builds the starting window in k steps. The second loop visits each remaining element once. Together that is O(n) work. We only keep a couple of variables, so the extra memory is O(1).
Output
Sliding window runs in O(n) time and O(1) extra space. The slow recompute approach runs in O(n*k) time. On large arrays with a large k, that difference is huge.
| Approach | Time | Space |
|---|---|---|
| Recompute each subarray sum | O(n*k) | O(1) |
| Sliding window | O(n) | O(1) |
β οΈ Common Mistakes
A few things go wrong the first time. Watch for these.
- Forgetting to build the first window before the slide loop starts. The slide formula only works once you have a real starting sum.
- Subtracting the wrong element. The one leaving is
arr[i - k], notarr[i - 1]. Get the index right. - Starting the slide loop at the wrong index. It must start at
i = k, because indices0tok - 1are already inside the first window. - Not checking that
kis not larger than the array length. Ifkis too big, there is no valid window.
π§© What Youβve Learned
- β A sliding window is a fixed range of elements you carry across the array, adjusting instead of rebuilding.
- β
The slow way recomputes every subarray sum and costs
O(n*k). - β
Sliding adds the entering element and subtracts the leaving element, so it costs only
O(n). - β
The key line is
windowSum += arr[i] - arr[i - k]. - β Fixed window keeps a constant size; variable window grows and shrinks on a condition.
- β
Extra space stays at
O(1)because you only track a sum and a max.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Why is the sliding window faster than recomputing each subarray sum?
Why: Each slide just adds the entering element and subtracts the leaving one, so no full re-add is needed.
- 2
For a fixed window of size k, which element leaves the window when you move to index i?
Why: The element that was at the left edge, k positions back, is arr[i - k].
- 3
What is the time complexity of the sliding window for the max sum of size k?
Why: After building the first window, each remaining element is visited once, giving O(n).
- 4
What is the difference between a fixed window and a variable window?
Why: A fixed window stays the same size like k, while a variable window changes size to satisfy a condition.
π Whatβs Next?
Want to keep going? These two pair well with sliding window: