Sliding Window in Python: Stop Recalculating the Same Things Again and Again
Imagine you are standing in front of a long street full of houses.
You want to know how much money is spent in every group of 3 consecutive houses.
For example:
[10, 20, 30, 40, 50]If the window size is 3, you want:
10 + 20 + 30 = 60
20 + 30 + 40 = 90
30 + 40 + 50 = 120A beginner might think:
“Easy! I will calculate each sum separately.”
And that works.
But there is a small problem.
We are calculating the same numbers again and again.
This is exactly the kind of problem where the Sliding Window technique becomes extremely useful.
Today, let’s understand Sliding Window from scratch using Python.
No complicated mathematics.
No scary algorithms.
Just one window moving across an array.
What is Sliding Window?
Sliding Window is a technique used when we need to work with a continuous part of an array or string.
Think about a physical window.
You can see only a few houses through the window at a time.
Then you move the window to the right.
The window still has the same size, but it now shows a new group of houses.
For example:
Array:
[10, 20, 30, 40, 50]
Window size = 3Our first window is:
[10, 20, 30] 40 50Then we slide it:
10 [20, 30, 40] 50Then again:
10 20 [30, 40, 50]That’s Sliding Window.
The important idea is this:
Instead of calculating everything from scratch, reuse the information from the previous window.
The Problem With the Normal Approach
Let’s say we have:
numbers = [10, 20, 30, 40, 50]
k = 3We want the maximum sum of any 3 consecutive numbers.
A straightforward solution could be:
numbers = [10, 20, 30, 40, 50]
k = 3
maximum = 0
for i in range(len(numbers) - k + 1):
current_sum = sum(numbers[i:i + k])
maximum = max(maximum, current_sum)
print(maximum)Output:
120This works.
But look carefully at what happens.
First:
10 + 20 + 30Then:
20 + 30 + 40Then:
30 + 40 + 50Notice something?
When we move from the first window to the second window:
[10, 20, 30]becomes:
[20, 30, 40]We already know the sum of:
20 + 30Why calculate them again?
We don’t need to.
We can simply:
- Remove the number leaving the window
- Add the number entering the window
That is the magic of Sliding Window.
The Sliding Window Idea
Let’s calculate the first window:
[10, 20, 30]Its sum is:
60Now move the window one position to the right.
The 10 leaves.
The 40 enters.
So instead of calculating:
20 + 30 + 40again, we do:
60 - 10 + 40which gives:
90Then move again.
The 20 leaves.
The 50 enters.
90 - 20 + 50Result:
120We avoided unnecessary calculations.
Implementing Sliding Window in Python
Here is the basic implementation:
numbers = [10, 20, 30, 40, 50]
k = 3
window_sum = sum(numbers[:k])
maximum = window_sum
for right in range(k, len(numbers)):
window_sum += numbers[right]
window_sum -= numbers[right - k]
maximum = max(maximum, window_sum)
print(maximum)Output:
120Let’s understand this slowly.
Step 1: Create the first window
window_sum = sum(numbers[:k])Since k = 3:
numbers[:3]gives:
[10, 20, 30]So:
window_sum = 60We store this as our current maximum:
maximum = window_sumStep 2: Start Sliding
Now we start from index 3:
for right in range(k, len(numbers)):Our array indexes are:
0 1 2 3 4
[10, 20, 30, 40, 50]Index 3 contains 40.
So our new window becomes:
[20, 30, 40]We add 40:
window_sum += numbers[right]Now:
60 + 40 = 100But we still have the 10 from the previous window.
So we remove it:
window_sum -= numbers[right - k]Here:
right = 3
k = 3right - k = 0Index 0 contains 10.
Therefore:
100 - 10 = 90Our new window sum is:
90Beautiful.
Visualizing the Movement
This is probably the easiest way to remember Sliding Window.
Start:
[10, 20, 30] 40 50Sum:
60Move right:
10 [20, 30, 40] 50Remove 10.
Add 40.
60 - 10 + 40 = 90Move again:
10 20 [30, 40, 50]Remove 20.
Add 50.
90 - 20 + 50 = 120The window is literally sliding across the array.
Why Is Sliding Window Faster?
Suppose the array contains n elements and the window size is k.
With the straightforward approach, we repeatedly calculate sums containing k elements.
This can take:
O(n × k)With Sliding Window, each element enters the window once and leaves the window once.
Therefore, the time complexity becomes:
O(n)That can make a huge difference when the input becomes large.
For example, imagine:
n = 1,000,000
k = 100,000Recalculating every window can perform a massive number of unnecessary operations.
Sliding Window avoids that repetition.
A Simple Real-World Example
Imagine you are tracking the number of steps you take every day.
steps = [5000, 7000, 6000, 8000, 10000, 9000]You want to find the maximum number of steps taken over any 3 consecutive days.
The windows are:
[5000, 7000, 6000]Sum:
18000Next:
[7000, 6000, 8000]Sum:
21000Next:
[6000, 8000, 10000]Sum:
24000Next:
[8000, 10000, 9000]Sum:
27000So the answer is:
27000With Sliding Window:
steps = [5000, 7000, 6000, 8000, 10000, 9000]
k = 3
window_sum = sum(steps[:k])
maximum = window_sum
for right in range(k, len(steps)):
window_sum += steps[right]
window_sum -= steps[right - k]
maximum = max(maximum, window_sum)
print(maximum)Output:
27000Fixed Size Sliding Window
What we have discussed so far is called a Fixed Size Sliding Window.
The window always has the same size.
For example:
k = 3Every window contains exactly 3 elements.
The pattern usually looks like this:
window_sum = sum(numbers[:k])
for right in range(k, len(numbers)):
window_sum += numbers[right]
window_sum -= numbers[right - k]This pattern is extremely useful for problems involving:
Maximum sum of k elements
Minimum sum of k elements
Average of every k consecutive elements
Maximum number of something inside k consecutive positions
Finding patterns inside a fixed length substringBut Sliding Window Is Not Always Fixed
This is where Sliding Window becomes more interesting.
Sometimes we don’t know the window size beforehand.
Instead, we expand and shrink the window depending on a condition.
For example:
Find the smallest subarray whose sum is at least 7.
Consider:
numbers = [2, 3, 1, 2, 4, 3]We want the smallest continuous section whose sum is at least 7.
Get Gulsaba Fiha’s stories in your inbox
Join Medium for free to get updates from this writer.
Start expanding:
[2]Sum:
2Expand:
[2, 3]Sum:
5Expand:
[2, 3, 1]Sum:
6Expand:
[2, 3, 1, 2]Sum:
8Now our condition is satisfied.
But we want the smallest possible window.
So we start removing elements from the left.
Remove 2:
[3, 1, 2]Sum:
6The condition is no longer satisfied.
So we stop shrinking.
Then continue expanding.
This is called a Dynamic Sliding Window.
The Two Pointer Pattern
Dynamic Sliding Window commonly uses two pointers.
We usually call them:
left
rightThink of them as the two sides of our window.
For example:
left
↓
[2, 3, 1, 2, 4, 3]
↑
rightThe right pointer expands the window.
The left pointer shrinks the window.
So we get a pattern like:
left = 0
for right in range(len(numbers)):
# Add numbers[right]
while condition_is_not_valid:
# Remove numbers[left]
left += 1This pattern appears again and again in coding interviews and LeetCode problems.
Dynamic Sliding Window Example
Let’s solve the previous problem.
Find the minimum length subarray whose sum is at least 7.
numbers = [2, 3, 1, 2, 4, 3]
target = 7
left = 0
current_sum = 0
minimum_length = float("inf")
for right in range(len(numbers)):
current_sum += numbers[right]
while current_sum >= target:
window_length = right - left + 1
minimum_length = min(minimum_length, window_length)
current_sum -= numbers[left]
left += 1
print(minimum_length)Output:
2Why?
Because:
[4, 3]has a sum of:
7and its length is:
2Understanding This Code
This line:
current_sum += numbers[right]means:
The right side of the window moved forward, so add the new element.
Then:
while current_sum >= target:means:
Our window is currently valid. Can we make it smaller?
Then:
current_sum -= numbers[left]
left += 1means:
Remove the leftmost element and move the left pointer forward.
This is the heart of dynamic Sliding Window.
A Very Important Detail
You should not blindly use Sliding Window for every array problem.
Sliding Window works especially well when the problem involves a continuous section of an array or string.
Look for words such as:
contiguous
consecutive
substring
subarray
window
longest
shortest
maximum
minimum
at most
at leastThese words should make you think:
“Could Sliding Window help here?”
Sliding Window With Strings
Sliding Window is not only for numbers.
It is extremely common with strings.
For example:
Find the length of the longest substring without repeating characters.
Consider:
abcabcbbThe answer is:
3because:
abcis the longest substring without duplicate characters.
We can use a Sliding Window with a set.
text = "abcabcbb"
characters = set()
left = 0
maximum_length = 0
for right in range(len(text)):
while text[right] in characters:
characters.remove(text[left])
left += 1
characters.add(text[right])
window_length = right - left + 1
maximum_length = max(maximum_length, window_length)
print(maximum_length)Output:
3Here the window size is not fixed.
It grows until we find a duplicate.
Then we shrink it from the left until the window becomes valid again.
Fixed Window vs Dynamic Window
This distinction is important.
Fixed Window
The size is known.
Example:
Find the maximum sum of 3 consecutive numbers.We know:
k = 3The window always contains 3 elements.
Typical pattern:
for right in range(k, len(numbers)):
...Dynamic Window
The size changes according to a condition.
Example:
Find the longest substring without repeating characters.The window can contain:
1 character
2 characters
3 characters
10 charactersdepending on the situation.
Typical pattern:
left = 0
for right in range(len(numbers)):
while condition:
left += 1LeetCode Problems You Should Practice
Once you understand the basic idea, practice these problems.
1. Maximum Average Subarray I
LeetCode 643
This is a great first Sliding Window problem.
You are given an array and an integer k.
Find the maximum average of any contiguous subarray of length k.
This is a perfect example of a Fixed Size Sliding Window.
Think:
Create first window
Calculate its sum
Slide right
Add the new element
Remove the old element
Track maximum2. Minimum Size Subarray Sum
LeetCode 209
This is a great introduction to Dynamic Sliding Window.
You need to find the smallest contiguous subarray whose sum is at least a target.
Think:
Expand right
When condition is satisfied
Shrink from left
Keep track of the smallest window3. Longest Substring Without Repeating Characters
LeetCode 3
This is one of the most famous Sliding Window problems.
It introduces Sliding Window with strings and a set.
Think:
Expand right
If duplicate appears
Move left until duplicate disappears
Track maximum length4. Longest Repeating Character Replacement
LeetCode 424
This is a slightly more advanced Sliding Window problem.
It teaches you how to maintain information about the current window while deciding whether the window is still valid.
5. Permutation in String
LeetCode 567
This combines Sliding Window with character frequency counting.
It is a very good problem once you are comfortable with Fixed Size Windows.
6. Find All Anagrams in a String
LeetCode 438
Another excellent problem for understanding Fixed Size Sliding Window with frequency maps.
My Recommended Learning Order
Don’t jump directly into the hardest problems.
Try them in this order:
1. Maximum Average Subarray I
2. Minimum Size Subarray Sum
3. Longest Substring Without Repeating Characters
4. Find All Anagrams in a String
5. Permutation in String
6. Longest Repeating Character ReplacementIf you can solve these without looking at the solution, you are starting to understand Sliding Window really well.
The Mental Model I Use
Whenever I see a problem involving a continuous part of an array or string, I ask myself three questions.
Question 1
Is the problem asking about a contiguous section?
If yes, Sliding Window might be useful.
Question 2
Is the window size fixed?
If yes, think:
Add right
Remove leftQuestion 3
Is the window size changing based on a condition?
If yes, think:
Expand with right
Shrink with leftThat’s basically the whole idea.
The Cheat Sheet
When you see:
Fixed size
window_sum = sum(numbers[:k])Think:
for right in range(k, len(numbers)):
window_sum += numbers[right]
window_sum -= numbers[right - k]When you see:
Variable size
left = 0Think:
for right in range(len(numbers)): # Add right element while condition_is_not_valid:
# Remove left element
left += 1
And when you see:
Longest
Shortest
Maximum
Minimum
Substring
Subarray
Consecutive
ContiguousPause for a second and ask:
Can I solve this by moving a window instead of recalculating everything?
Very often, the answer is yes.
Final Thought
Sliding Window might look like a complicated algorithm when you first hear the name.
But the idea is actually quite simple.
Imagine a window moving across an array.
Instead of throwing away everything we calculated for the previous window, we keep the useful information.
Something leaves the window.
We remove it.
Something enters the window.
We add it.
That’s it.
The real skill is not memorizing the code.
The real skill is recognizing when a problem has a window hiding inside it.
Once you start seeing that pattern, a lot of array and string problems on LeetCode suddenly become much less intimidating.
So next time you see a problem asking about a contiguous subarray or substring, don’t immediately start writing nested loops.
First ask yourself:
“Can I slide a window?”










