Sliding Window in Arrays — A Beginner’s Mental Model
Source: Dev.to
What Is a Sliding Window?
A sliding window is a technique for processing a continuous part of an array (or string) while reusing previous calculations.
Instead of recomputing everything for each new subarray, you:
- Compute the result for the first window.
- Slide the window forward by removing the element that leaves and adding the element that enters.
That’s it.
When to Use a Sliding Window
Use it whenever a problem asks for something about a subarray / substring, especially when the statement mentions:
- “subarray of size K”
- “maximum/minimum sum of any K‑length window”
In such cases, a naïve approach would:
- Loop over every possible subarray.
- Re‑sum all elements each time → O(N·K) time.
With a sliding window you achieve O(N) time by updating the result incrementally.
Example
Consider the array:
[5, 2, 7, 1]
K = 3
First window ([5, 2, 7]) → Sum = 14
Slide one step →
- Leaving element:
5 - New window:
[2, 7, 1] - Updated sum:
14 - 5 + 1 = 10
No full recalculation is needed.
How Pointer Movement Works
Fixed‑size sliding window
Let k be the window size. For each step i (starting at i = k):
- Leaving element =
arr[i - k] - Entering element =
arr[i]
You don’t need an explicit “left pointer”; the arithmetic takes care of it.
Sample Code (C++)
double maxSumSubarray(vector nums, int k) {
int windowSum = 0;
// first window
for (int i = 0; i (maxSum) / k;
}
If you can explain the steps above clearly, you can translate them into code for any language.
Example Input to Validate Your Understanding
nums = [1, 12, -5, -6, 50, 3]
k = 4
The windows are:
[1, 12, -5, -6][12, -5, -6, 50][-5, -6, 50, 3]
Each slide removes one element and adds one new element, allowing the sum (or any aggregate) to be updated with a simple subtract + add operation. No extra loops are required.
Key Takeaway
The sliding‑window technique isn’t magic; it’s simply:
“Reuse the previous result by removing what leaves and adding what enters.”
By doing so, you avoid redundant calculations and achieve linear‑time solutions for many subarray/subsequence problems.