When I first heard Sliding Window, my confusion was:
- Why not recalculate every time?
- Which element leaves? Which enters?
- How do pointers actually move?
This article explains sliding window only at the thinking level, not fancy tricks.
What Is Sliding Window?
Sliding Window is a technique where:
- You look at a continuous part of an array
- You reuse previous calculations
- You slide the window forward by removing one element and adding one new element
- Instead of recalculating everything again.
Where Do We Use Sliding Window?
Use sliding window when you see:
Subarray / substring
Fixed size K or at most K
Maximum / minimum / sum / count
Contiguous elements
If the problem says:
“subarray of size K”
👉 Sliding window is the first thing to try.
Why Sliding Window Exists (No Recalculation)
Brute Force Thinking
- For every subarray:
- Loop again
- Add everything again
- Waste time
Sliding Window Thinking
- Calculate once
- Remove what leaves
- Add what enters
That’s it.
Fixed Window Example (Core Idea)
Array:
[5, 2, 7, 1]
K = 3
First window
[5, 2, 7]
Sum = 14
Slide window by 1 step →
Leaving element → 5
Entering element → 1
Second window
[2, 7, 1]
Sum = 14 - 5 + 1 = 10
👉 No full recalculation
👉 Just subtract + add
How Pointer Movement Works
For fixed sliding window:
k = window size
First window → indices 0 to k-1
After that, right pointer moves forward
Left pointer automatically becomes i - k
Pointer rule
Leaving element = arr[i - k]
Entering element = arr[i]
You don’t explicitly move left pointer — math does it.
English Explanation Before Coding
“First, calculate the sum of the first K elements.
Then, for each next element:
remove the element that goes out of the window
add the new element that comes into the window
Update the answer.”
If you can say this clearly → you can code it.
Code (Fixed Window Sliding)
double maxSumSubarray(vector<int> nums, int k) {
int windowSum = 0;
// first window
for (int i = 0; i < k; i++) {
windowSum += nums[i];
}
int maxSum = windowSum;
// slide window
for (int i = k; i < nums.size(); i++) {
windowSum -= nums[i - k]; // leaving
windowSum += nums[i]; // entering
maxSum = max(maxSum, windowSum);
}
return (float)maxSum / k;
}
Input to Validate Your Mind
nums = [1, 12, -5, -6, 50, 3]
k = 4
Windows:
[1, 12, -5, -6]
[12, -5, -6, 50]
[-5, -6, 50, 3]
Only one element leaves and one enters each time.
Why Sliding Window Is Used for Sum / Count
Because:
- Sum can be updated by subtract + add
- Count can be updated by remove + include
- No need to loop again
- That’s the non-recalculation advantage.
Final Mental Model
Sliding Window is not magic.
It is simply:
“Reuse the previous result by removing what leaves and adding what enters.”
Top comments (0)