Lesson 7 of 40Core patterns
Sliding Window
Turn nested loops over ranges into a single pass by growing and shrinking a window.
Some problems ask about contiguous pieces of an array or string: the best 3-day stretch, the longest substring without repeats, the smallest subarray that adds up to at least 7. The beginner move is to check every range with two loops. That is O(n²), and an interviewer will ask you to do better.
The sliding window does it in one pass. You keep a range [left, right], and move its edges forward instead of starting over.
The idea in one picture
Say we want the biggest sum of any 3 numbers in a row. Start with the first three, then slide: one number comes in on the right, one leaves on the left.
Add up the first three: 2 + 1 + 5 = 8. That is our best so far.
Each step costs one addition and one subtraction, whatever the window size. Four steps instead of re-adding three numbers four times. On a million numbers with k = 1000, that is the difference between a billion operations and two million.
Two flavours
Fixed size. The window is always k wide. Build it once, then slide it one step at a time. Use it for "best / average / count over every k in a row".
window = sum(nums[:k])
for right in range(k, len(nums)):
window += nums[right] - nums[right - k]Variable size. The window grows on the right and shrinks on the left whenever a rule breaks. Use it for "longest / shortest range where some condition holds".
left = 0
for right in range(len(s)):
add(s[right])
while rule_is_broken():
remove(s[left])
left += 1
best = max(best, right - left + 1)Watching a variable window
Longest substring with no repeated letters in "abcabcbb". The set holds what is inside the window.
Start with just a.
Try it
Run this, then change k and run it again.
Press Run (⌘ Enter) to see what happens.What does this print?
nums = [4, 2, 1, 7, 8] k = 2 window = nums[0] + nums[1] window += nums[2] - nums[0] print(window)
Put the variable-window loop body in order.
- Tap the steps below in the right order.
Spot the pattern
Which problems are sliding windows?
Fixed window with a counts array: Permutation in String
Does s contain some rearrangement of p as a contiguous piece? A rearrangement has exactly the same letter counts, and it has exactly len(p) letters. So slide a fixed window of that width over s and compare counts. For lowercase letters a list of 26 integers is the cheapest exact signature: comparing two of them is 26 steps however long the strings are, which is O(1).
Press Run (⌘ Enter) to see what happens.This is O(26 · n), which is O(n). String Algorithms uses the same window for Find All Anagrams, and covers why sorting each window instead would cost O(k log k) per step. If you want to skip even the 26-step comparison, keep a single matches counter of how many of the 26 slots agree, and update it as each slot changes. It is faster, but easier to get wrong, so mention it rather than lead with it.
Minimum Window Substring: need and have
Find the shortest piece of s that contains every character of t, with repeats counted. This is the hard variable window, and it flips the usual shape: the window is valid when it covers t, and you shrink while it stays valid to find the shortest one. The longest-window problems earlier did the opposite, shrinking while the window was invalid.
Checking "does the window cover t?" by comparing two whole count maps at every step would be slow. Instead keep two numbers:
need: the count of each character int, andrequired = len(need), the number of distinct characters you must satisfy.have: how many distinct characters currently meet their required count.
When a character enters and its window count reaches its need exactly, have goes up by one. When one leaves and its count drops below its need, have goes down. Extra copies change nothing. The window is valid exactly when have == required, and that check is O(1).
Grow until all of A, B and C are covered. At R = 5 the window ADOBEC is valid. Record length 6.
Press Run (⌘ Enter) to see what happens.The two equality tests are where bugs live. Use == need[ch] on the way in, not >=, or a third copy of A would bump have again. Use < need[out] on the way out, so dropping a spare copy does not count as losing coverage. Each index enters once and leaves once, so the whole thing is O(|s| + |t|).
Longest Repeating Character Replacement and the lazy maxFreq
Given a string and k, you may change up to k letters. What is the longest run of one repeated letter you can make? A window is fixable when the letters that are not its most common letter number at most k: window_length - max_freq <= k.
Here is the surprising part. The standard solution keeps a max_freq that only ever goes up, even when the letter that set it slides out of the window. And it shrinks with if, not while, against the common-mistakes advice below. Both are deliberate.
Press Run (⌘ Enter) to see what happens.Why it is still correct: you only care about windows longer than the best one so far. A longer valid window needs length - freq <= k with a bigger length, so it needs a bigger freq than any you have seen. Until a letter count beats the old max_freq, no new answer is possible, so a stale, too-high max_freq cannot cause a wrong answer. It only lets the window slide along at its current width instead of shrinking. That is also why one if is enough: the window never needs to get smaller, only to stop growing. When a real new maximum appears, the window grows by one and best updates.
If you prefer the version you can defend in one sentence, recompute the true maximum over the 26 counts inside a while loop. It is O(26 · n) and equally accepted. Knowing why the lazy version works is what separates a memorised answer from an understood one.
Exactly K: atMost(K) - atMost(K - 1)
"Count subarrays with exactly K different integers" does not fit the window directly. When the window has exactly K distinct values, adding an element might keep it at K or push it to K + 1, and removing one might drop it to K − 1, so there is no single rule that says "shrink now". The window cannot tell which way to move.
"At most K" does fit. The rule "shrink while more than K distinct" is clean, and once the window [left, right] is valid, every subarray that ends at right and starts anywhere from left to right is also valid. That is right - left + 1 subarrays, added in one step. Then:
exactly(K) = atMost(K) - atMost(K - 1)
Subarrays with at most K distinct values, minus those with at most K − 1, leaves those with exactly K.
Press Run (⌘ Enter) to see what happens.The same subtraction solves "count subarrays with exactly K odd numbers" and "binary subarrays with sum equal to goal" (for those two, Prefix Sums and Difference Arrays shows a prefix-count alternative). Forgetting the del is the classic bug: a key with count 0 still counts toward len(counts), and the window shrinks too far.
What does this print?
print(at_most([1, 2, 1, 2, 3], 2), at_most([1, 2, 1, 2, 3], 1), exactly([1, 2, 1, 2, 3], 2))
atMost(K) - atMost(K - 1) instead of one window?Common mistakes
- Using a window when the answer is not contiguous. "Pick any 3 numbers with the biggest sum" is a sort or a heap, not a window. The window only works when the elements must sit next to each other.
- Shrinking with
ifinstead ofwhile. One step left is not always enough. Keep shrinking until the window is valid again. - Recording the answer before repairing the window. Update
bestonly after the inner loop, when you know the window obeys the rule. - Off-by-one on the width. A window from
lefttorightinclusive holdsright - left + 1items. - Negative numbers in "sum at least k" problems. Shrinking only works when adding an element can never make the sum smaller. With negatives, reach for prefix sums and a hash map instead (Prefix Sums and Difference Arrays), or a monotonic deque over prefix sums for the shortest version (Monotonic Stacks and Queues).
More to practice
Once these feel easy, try Best Time to Buy and Sell Stock (a window where the left edge jumps to a new low), Fruit Into Baskets (at most 2 distinct, the at_most function above with k = 2), and Sliding Window Maximum, which needs a deque that keeps its values in order and is covered in Monotonic Stacks and Queues. Then come back to Minimum Window Substring and write it from a blank page. All of them are in Practice under Sliding Window.
Best k-day streak
Given a list of daily sales nums and a window size k, return the largest sum of any k consecutive days.
nums = [2, 1, 5, 1, 3, 2], k = 3 → 9 (5 + 1 + 3)
nums = [-3, -1, -2], k = 1 → -1Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Longest Substring Without Repeating Characters
Given a string s, return the length of the longest substring that has no repeated characters. A substring is a contiguous run of characters, so "pwke" does not count for "pwwkew".
"abcabcbb" → 3 ("abc")
"bbbbb" → 1 ("b")
"pwwkew" → 3 ("wke")Constraints
0 <= s.length <= 5 * 10^4sconsists of English letters, digits, symbols and spaces.
- window
- The current contiguous range
[left, right]you are looking at. - fixed window
- Always exactly k wide. Slide by adding one element and removing one.
- variable window
- Grows on the right and shrinks on the left whenever a rule breaks.
- amortized O(n)
- Each element enters and leaves the window at most once, so the total work is linear even with an inner loop.
- need / have counters
- For coverage windows:
needholds required counts,havecounts how many distinct characters currently meet them, so validity is an O(1) check. - atMost(K) - atMost(K-1)
- Turns an 'exactly K' count, which has no clean shrink rule, into two 'at most' windows that do.
- lazy max_freq
- In character replacement, the best frequency seen so far is never lowered, because only a higher one can produce a longer answer.