A sliding window is a contiguous range [left, right] that moves across an array or string. Instead of recomputing every subarray from scratch, you update the answer as one element enters on the right and another leaves on the left. That turns O(n·k) or O(n²) scans into a single O(n) pass, and it is the go-to pattern for "longest, shortest or count of contiguous subarrays or substrings that satisfy a condition".
Think of it like
A caterpillar crawling along a branch
A caterpillar stretches its head forward to grab new ground, and when its body gets too long (or the constraint breaks) it pulls its tail forward to catch up. Head and tail only ever move forward, so even though it stretches and contracts many times, each point on the branch is passed by the head once and by the tail once.
How to recognize it
- The question is about a contiguous subarray or substring, not a subsequence.
- It asks for the longest, shortest, maximum, minimum or number of such ranges.
- The validity condition can be updated incrementally when one element enters or leaves: a running sum, a frequency map, a count of distinct values, a count of "bad" characters.
- A fixed window size
kis given ("every block of k days", "each substring of length k").
Fixed-size windows
When the size k is fixed, the window slides one step at a time: add the element entering on the right, remove the one leaving on the left. Each step is O(1), so all n - k + 1 windows cost O(n) instead of O(n·k).
| Window | Elements | Update | Sum |
|---|---|---|---|
[0, 2] | 2, 1, 5 | initial | 8 |
[1, 3] | 1, 5, 1 | +1 − 2 | 7 |
[2, 4] | 5, 1, 3 | +3 − 1 | 9 (best) |
[3, 5] | 1, 3, 2 | +2 − 5 | 6 |
[2, 1, 5, 1, 3, 2].def fixed_window(a, k):
state = init()
best = None
for right in range(len(a)):
add(state, a[right]) # element enters
if right >= k:
remove(state, a[right - k]) # element leaves
if right >= k - 1:
best = better(best, answer(state)) # window [right-k+1, right] is complete
return bestVariable-size windows
When the size is not given, the window grows by moving right every iteration and shrinks by moving left only as much as needed to restore validity. The visualization above shows the two edges moving independently: the right edge advances steadily while the left edge jumps forward whenever the constraint breaks.
def longest_valid(a):
state = init()
left = 0
best = 0
for right in range(len(a)):
add(state, a[right])
while not valid(state): # shrink until the window is valid again
remove(state, a[left])
left += 1
best = max(best, right - left + 1) # [left, right] is the longest valid window ending at right
return bestLongest valid window
- Shrink while invalid
- Record the answer after the shrink loop
- Examples: longest substring without repeats, at most K distinct, longest with sum ≤ S
Shortest valid window
- Shrink while valid
- Record the answer inside the shrink loop, before removing
- Examples: minimum size subarray sum ≥ S, minimum window substring
Classic problems
Longest substring without repeating characters
The window is valid when every character in it is unique. Keep a count (or last-seen index) per character. When s[right] is already inside the window, move left past its previous occurrence.
| right | char | Action | Window | Best |
|---|---|---|---|---|
| 0 | a | add | a | 1 |
| 1 | b | add | ab | 2 |
| 2 | c | add | abc | 3 |
| 3 | a | repeat: left jumps past the old a (index 0) | bca | 3 |
| 4 | b | repeat: left jumps past index 1 | cab | 3 |
| 5 | c | repeat: left jumps past index 2 | abc | 3 |
| 6 | b | repeat: left jumps past index 4 | cb | 3 |
| 7 | b | repeat: left jumps past index 6 | b | 3 |
"abcabcbb" with the last-seen-index optimization: left = max(left, last[c] + 1).Minimum window substring
- 1
Count the requirement
Build
need[c]from stringtand setmissing = len(t), the number of characters still to cover. - 2
Expand
Move
right. Ifneed[s[right]] > 0, this character covers a requirement, so decrementmissing. Always decrementneed[s[right]](it may go negative for surplus characters). - 3
Shrink while valid
While
missing == 0, the window coverst. Record it if it is the shortest so far, then removes[left]: incrementneed[s[left]], and if it becomes positive, a requirement is uncovered, so incrementmissing. - 4
Repeat
Continue until
rightreaches the end. Every index enters and leaves once: O(|s| + |t|).
At most K distinct characters
Maintain a frequency map of the window. After adding s[right], while the map has more than K keys, decrement s[left] and delete it when its count reaches zero. Fruit Into Baskets is exactly this problem with K = 2.
Counting windows: exactly K = atMost(K) − atMost(K − 1)
Counting subarrays with exactly K distinct values does not fit the template directly: shrinking a window with exactly K distinct values can drop it to K − 1, so there is no single "valid" region to maintain. But "at most K" is monotone, and counting it is easy: for each right, every start in [left, right] gives a valid window, so add right - left + 1.
from collections import defaultdict
def at_most(nums: list[int], k: int) -> int:
count: dict[int, int] = defaultdict(int)
left = total = 0
for right, x in enumerate(nums):
count[x] += 1
while len(count) > k:
count[nums[left]] -= 1
if count[nums[left]] == 0:
del count[nums[left]]
left += 1
total += right - left + 1 # windows ending at right
return total
def exactly_k(nums: list[int], k: int) -> int:
return at_most(nums, k) - at_most(nums, k - 1)When sliding window fails
The variable window depends on monotonicity: if a window is valid, so is every window inside it (for "longest" problems), or if a window is valid, so is every window containing it (for "shortest" problems). That is what justifies throwing away the left side for good.
Negative numbers break this for sums. Adding an element can make the sum smaller, and removing one can make it larger, so you can no longer tell which edge to move. Switch tools:
| Problem | Non-negative values | With negative values |
|---|---|---|
| Count subarrays with sum = k | Sliding window (or atMost trick) | Prefix sums + hash map, see Prefix Sums & Difference Arrays |
| Shortest subarray with sum ≥ k | Variable sliding window | Monotonic deque over prefix sums, see Monotonic Stack & Queue |
| Longest subarray with sum ≤ k | Variable sliding window | Prefix sums + binary search on a monotone prefix maximum |
| Maximum subarray sum | Whole array | Kadane's algorithm (a DP, not a window) |
Complexity and edge cases
Both templates run in O(n) time because each pointer moves at most n times. Space is O(1) for numeric state, or O(σ) for a frequency map over an alphabet of size σ (26 for lowercase letters, up to n for arbitrary values).
k > nin a fixed window: there is no complete window, so return the problem's empty answer.- Empty string or array: the loop never runs; make sure the default answer (0, empty string) is correct.
- Minimum-length problems: initialize the best length to infinity and map "never found" to 0 or
"". - Delete keys whose count reaches zero, otherwise
len(count)overstates the number of distinct values.
Complexity
| Problem | Time | Space | Notes |
|---|---|---|---|
| Max sum of size k | O(n) | O(1) | Fixed window |
| Longest substring without repeats | O(n) | O(σ) | σ = alphabet size |
| Minimum window substring | O(|s| + |t|) | O(σ) | Shrink while valid |
| At most K distinct | O(n) | O(K) | Frequency map with at most K + 1 keys |
| Exactly K distinct | O(n) | O(K) | Two atMost passes |
| Brute force over all windows | O(n²) | O(1) | What the pattern replaces |
Each index is added once and removed at most once, so variable windows are amortized O(n).
Implementation
Slide a window of exactly k elements, updating the sum in O(1) per step.
def max_sum_k(nums: list[int], k: int) -> int | None:
if k <= 0 or k > len(nums):
return None
window = sum(nums[:k])
best = window
for right in range(k, len(nums)):
window += nums[right] - nums[right - k] # one enters, one leaves
best = max(best, window)
return bestKey takeaways
- Use a sliding window for contiguous subarrays or substrings whose validity can be updated as elements enter and leave.
- Fixed windows add one element and remove one per step; variable windows grow on the right and shrink on the left.
- Both pointers only move forward, so variable windows are amortized O(n) despite the nested loop.
- For "longest", shrink while invalid and record after; for "shortest", shrink while valid and record inside the loop.
- Count exactly K with
atMost(K) - atMost(K - 1). - Negative numbers break window monotonicity for sums: use prefix sums with a hash map or a monotonic deque.
Common pitfalls
- Applying a window to a subsequence problem, where elements may be skipped.
- Using a variable window for sums when values can be negative.
- Moving
leftbackwards with the last-seen-index trick (forgettingmax(left, last[c] + 1)). - Leaving zero-count keys in the frequency map, which inflates the distinct count.
- Recording the answer at the wrong place: after the shrink loop for longest, inside it for shortest.
Interview tips
- Say the invariant out loud: "the window
[left, right]is always valid after the shrink loop". - Justify O(n) with the amortized argument: each index enters once and leaves once.
- When asked to count windows with an exact property, reach for the atMost subtraction trick.
- Ask whether values can be negative before choosing between a window and prefix sums.
Real-world applications
- Rate limiters that count requests in a sliding time window.
- Moving averages and rolling metrics in monitoring dashboards.
- TCP's sliding window for flow control.
- Streaming analytics: top values or distinct counts over the last N events.
Practice problems
Test yourself
The variable-size window has a while loop inside a for loop. Why is it still O(n)?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.