Sliding Window Technique
A sliding window keeps a running summary of a contiguous range, a sum, a count or a frequency map, and updates it as the range's ends move instead of recomputing it. That turns O(n·k) or O(n²) scans into O(n).
Reusing the Overlap
The sliding window technique is for questions about contiguous ranges: subarrays or substrings. Two neighbouring windows share everything except one value at each end, so after the first window there is no need to look at the whole range again. Subtract the value that leaves, add the value that enters, and the new answer is ready in O(1).
The running value is the window's summary: a sum, a count, a frequency map of characters. It works as long as the summary can be updated both when a value enters and when one leaves. A sum can, because subtraction undoes addition. A maximum cannot: when the largest value leaves, the next largest is unknown without rescanning, which is why the maximum of every window needs a monotonic queue instead of one variable.
- It is a two pointers pattern where both pointers move in the same direction
- Counting characters in a fixed array of 26 or 128 slots is faster than a hash map for plain text
Windows of a Given Width
- Build the first window: sum the first k values
- For i from k to n − 1: add a[i] and subtract a[i − k]
- After each move, compare the window's value with the best so far
When the width k is given, both ends move together and the loop needs no decisions. On [2, 1, 5, 1, 3, 2] with k = 3 the sums are 8, 7, 9 and 6, each new one from the last with one addition and one subtraction, so the best is 9 from [5, 1, 3]. Recomputing every window would cost k additions each, O(n·k) in total; sliding costs O(n) whatever k is.
The usual bug is at the start. A single loop that records an answer from the very first index records sums of half-built windows. For a maximum of positive numbers that is harmless by luck; for a minimum it is wrong, because a partial window looks small. Record only once i >= k − 1, or build the first window in its own loop.
- If k > n there is no window at all; return early instead of reading past the end
- Sums, first negatives and the window maximum with a deque: fixed size sliding window
- Practice: maximum average subarray, permutation in string, find all anagrams, sliding window maximum
Windows That Grow and Shrink
- Move
rightone step and add a[right] to the summary - While the window breaks the condition, remove a[left] and move
leftone step - The window is valid again: record its length if it is the best so far
When the question gives a condition instead of a width, such as the longest subarray with sum ≤ 7 or the longest substring with no repeated character, the two ends move separately. right always moves forward and adds a value; left moves only when the window has broken the condition, and stops as soon as it is fixed.
The code looks quadratic because of the inner while, but it is O(n). left never moves backwards and can move at most n times over the whole run, so the inner loop does at most n steps in total. Each value enters the window once and leaves at most once.
Longest and shortest questions shrink for opposite reasons, and mixing them up is the most common mistake:
| Question | Shrink while | Record | Example |
|---|---|---|---|
| Longest valid window | the window is invalid | after shrinking | longest substring without repeating characters |
| Shortest valid window | the window is still valid | before each shrink | minimum size subarray sum |
- Practice: longest substring without repeating characters, minimum size subarray sum, fruit into baskets, minimum window substring
- Keep validity an O(1) check, for example a count of characters that still need matching, not a scan of the whole frequency map
- The template, the exactly-k trick and counting windows: variable size sliding window
Terms, operations, and practical uses
Core vocabulary
- WindowA contiguous sequence of elements in an array or string bounded by two indices (left and right).
- Fixed SizeA window where the distance between the left and right pointers remains exactly K.
- Dynamic SizeA window that grows or shrinks as needed to satisfy a particular condition.
Operations
- ExpandIncreasing the window size by moving the right pointer and including a new element in the state.
- ShrinkDecreasing the window size by moving the left pointer and removing its element from the state.
- State UpdateModifying the running metric (sum, product, frequency map) in O(1) time when the window boundaries change.
Data structures
- Hash Map / DictionaryUsed to keep track of character frequencies or counts of elements currently inside the window.
- Frequency ArrayA fixed-size array (like
int[128]) often used instead of a Hash Map for ASCII string problems to improve speed. - DequeA double-ended queue used in monotonic sliding window problems (like finding the maximum in every window of size K).
Code in Python, C++ and Java
def max_sum(arr, k):
window_sum = sum(arr[:k])
max_val = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i-k]
max_val = max(max_val, window_sum)
return max_val
print(max_sum([2, 1, 5, 1, 3, 2], 3), '(from [5, 1, 3])')#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int maxSum(vector<int>& arr, int k) {
int windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
int maxVal = windowSum;
for (int i = k; i < arr.size(); i++) {
windowSum += arr[i] - arr[i - k];
maxVal = max(maxVal, windowSum);
}
return maxVal;
}
int main() {
vector<int> arr = {2, 1, 5, 1, 3, 2};
cout << maxSum(arr, 3) << " (from [5, 1, 3])\n";
}public class Main {
static int maxSum(int[] arr, int k) {
int windowSum = 0;
for (int i = 0; i < k; i++) windowSum += arr[i];
int maxVal = windowSum;
for (int i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
maxVal = Math.max(maxVal, windowSum);
}
return maxVal;
}
public static void main(String[] args) {
int[] arr = {2, 1, 5, 1, 3, 2};
System.out.println(maxSum(arr, 3) + " (from [5, 1, 3])");
}
}Step through it
Running on [2, 1, 5, 1, 3, 2], k = 3
When the Sliding Window Fails
A variable window relies on one rule: adding a value can only push the summary one way, and removing one can only pull it back. With non-negative numbers a sum only grows as the window grows, so shrinking is the right fix for a sum that is too big.
Negative numbers break that rule. Take the longest subarray of [5, −4, 1] with sum ≤ 2. The whole array sums to 2, so the answer is 3. The window sees 5 first, decides it is too big and throws it away, never learning that the −4 after it would have balanced it, and reports 2. For sums with negatives, use prefix sums with a hash map or a sorted structure instead: see subarray sum equals k.
Subsequences are not windows. A subsequence may skip values, so there is no contiguous range to slide; those questions are usually dynamic programming.
- Check the input constraints for negative values before reaching for a window
- "Exactly k" counts are rarely a direct window; compute atMost(k) − atMost(k − 1), as in subarrays with k different integers
Recognising a Sliding Window Problem
Three signs together point to a window: the question is about a contiguous range (subarray or substring), it asks for a longest, shortest, maximum or count over those ranges, and the obvious solution is two nested loops over every start and end. If the values are non-negative or the condition is a count of distinct items, the sliding window algorithm almost always applies.
The real design choice is the summary. A running sum or count handles arithmetic limits. A frequency map handles anagram, distinct-character and "contains all of" questions; pair it with one integer that says how many characters currently meet their target, so checking validity stays O(1) and the whole algorithm stays O(n).
- Fixed width given: fixed window. Condition given: variable window
- Values may be negative: prefix sums, not a window