When I first started solving array and string problems, Sliding Window was one of the patterns that felt confusing.
The code itself is usually short, but understanding when to move the window, what to remove, and what to add can be difficult at first.
This blog explains the Sliding Window technique from the basics with a simple example.
What is Sliding Window?
Sliding Window is a technique used to solve problems involving contiguous portions of an array or string.
Instead of repeatedly calculating the same elements, we maintain a window and move it through the input.
For example, consider:
nums = [1, 12, -5, -6, 50, 3]
If the window size is 4, our windows are:
[1, 12, -5, -6]
[12, -5, -6, 50]
[-5, -6, 50, 3]
The window moves one position at a time.
That is why it is called Sliding Window.
Why Do We Need Sliding Window?
Let's say we want to find the maximum sum of any k consecutive elements.
For:
nums = [1, 12, -5, -6, 50, 3]
k = 4
We could calculate every window from scratch:
1 + 12 + (-5) + (-6) = 2
12 + (-5) + (-6) + 50 = 51
(-5) + (-6) + 50 + 3 = 42
This works, but we are repeatedly calculating elements that were already included in the previous window.
Sliding Window avoids this unnecessary work.
The Main Idea
Look at the first window:
[1, 12, -5, -6] 50 3
Its sum is:
2
Now we slide the window one position to the right:
1 [12, -5, -6, 50] 3
What changed?
1 left the window.
50 entered the window.
So instead of calculating the entire sum again:
new sum = old sum - element leaving + element entering
Therefore:
new sum = 2 - 1 + 50
= 51
This simple idea is the heart of the fixed-size Sliding Window technique.
Fixed-Size Sliding Window
The general pattern looks like this:
window = sum(nums[:k])
for i in range(k, len(nums)):
window = window - nums[i-k] + nums[i]
The important line is:
window = window - nums[i-k] + nums[i]
It means:
Remove the element that is leaving
+
Add the element that is entering
Example: LeetCode 643
One beginner-friendly problem for learning Sliding Window is:
Maximum Average Subarray I
Given an integer array nums and an integer k, find the contiguous subarray of length k that has the maximum average.
For example:
nums = [1, 12, -5, -6, 50, 3]
k = 4
The possible windows are:
[1, 12, -5, -6] → sum = 2
[12, -5, -6, 50] → sum = 51
[-5, -6, 50, 3] → sum = 42
The maximum sum is:
51
Therefore, the maximum average is:
51 / 4 = 12.75
Python Solution
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
tot = sum(nums[:k])
avg = tot / k
maximum = avg
for i in range(k, len(nums)):
tot = tot - nums[i-k] + nums[i]
avg = tot / k
maximum = max(maximum, avg)
return maximum
Let's understand it step by step.
Step 1: Calculate the First Window
tot = sum(nums[:k])
If:
nums = [1, 12, -5, -6, 50, 3]
k = 4
then:
nums[:k]
gives:
[1, 12, -5, -6]
So:
tot = 2
Step 2: Calculate the First Average
avg = tot / k
Therefore:
avg = 2 / 4
= 0.5
We store this as our current maximum:
maximum = avg
Step 3: Slide the Window
Now we start from index k:
for i in range(k, len(nums)):
Since k = 4, the first value of i is 4.
The new element is:
nums[i]
which is:
nums[4] = 50
The element leaving the window is:
nums[i-k]
Since:
i = 4
k = 4
we get:
i - k = 0
Therefore:
nums[i-k] = nums[0] = 1
So:
tot = tot - nums[i-k] + nums[i]
becomes:
tot = 2 - 1 + 50
= 51
Our window has now moved from:
[1, 12, -5, -6]
to:
[12, -5, -6, 50]
Step 4: Update the Maximum
We calculate:
avg = tot / k
Therefore:
avg = 51 / 4
= 12.75
Then:
maximum = max(maximum, avg)
The maximum becomes:
12.75
The same process continues until we reach the end of the array.
The Pattern to Remember
For a fixed-size Sliding Window, remember these three steps:
1. Calculate the first window
window = sum(nums[:k])
2. Slide the window
window = window - nums[i-k] + nums[i]
3. Update the answer
answer = max(answer, window)
That's the basic pattern.
Time Complexity
A brute-force approach may repeatedly calculate the sum of every window.
Sliding Window allows us to update the sum in constant time for each movement.
Therefore:
Time Complexity: O(n)
Space Complexity: O(1)
where n is the number of elements in the array.
How to Recognize a Sliding Window Problem
When reading a LeetCode problem, look for words such as:
- contiguous
- consecutive
- substring
- subarray
- window
- exactly
k elements
- at most
k elements
- longest/shortest substring
- maximum/minimum sum of consecutive elements
For example:
Find the maximum sum of k consecutive elements.
This should immediately make you think:
Fixed-size Sliding Window.
Common Mistake
One common mistake is recalculating the entire window every time.
For example:
for i in range(n-k+1):
total = sum(nums[i:i+k])
This repeatedly calculates values that were already calculated.
Instead, calculate the first window once and then update it:
window = window - element_leaving + element_entering
Fixed vs Variable Sliding Window
There are two major types of Sliding Window.
Fixed-size window
The window size stays the same.
Example:
k = 4
[1, 2, 3, 4]
↓
[2, 3, 4, 5]
↓
[3, 4, 5, 6]
Problems such as Maximum Average Subarray I use this pattern.
Variable-size window
The window size can grow and shrink depending on a condition.
For example:
[ a b c d e ]
←──────→
The window may expand when the condition is valid and shrink when the condition is violated.
Variable-size Sliding Window is slightly more difficult, so it is better to learn fixed-size windows first.
Practice Roadmap
If you're new to Sliding Window, don't immediately jump into difficult problems.
A good progression is:
- LeetCode 643 — Maximum Average Subarray I
- LeetCode 1456 — Maximum Number of Vowels in a Substring of Given Length
- LeetCode 1343 — Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
- LeetCode 1876 — Substrings of Size Three with Distinct Characters
- LeetCode 209 — Minimum Size Subarray Sum
- LeetCode 3 — Longest Substring Without Repeating Characters
- LeetCode 1004 — Max Consecutive Ones III
- LeetCode 424 — Longest Repeating Character Replacement
The first four help build the fixed-size pattern.
The later problems introduce variable-size windows, which require a deeper understanding of when to expand and shrink the window.
Final Takeaway
Sliding Window is not a completely different way of thinking about arrays.
It is mainly about reusing information from the previous window instead of calculating everything again.
The most important idea is:
Remove what leaves.
Add what enters.
Move the window.
Update the answer.
Once this becomes familiar, many array and string problems that initially look complicated become much easier to recognize.
Start small, understand the pattern, and then increase the difficulty.