Skip to content

Lesson 7 of 40Core patterns

Sliding Window

Turn nested loops over ranges into a single pass by growing and shrinking a window.

20 min read0/7 questions

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.

Fixed window, k = 3
2
0
↑L
1
1
5
2
↑R
1
3
3
4
2
5
window = 8best = 8

Add up the first three: 2 + 1 + 5 = 8. That is our best so far.

1/4

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.

Quick check
Why is the sliding version O(n) even though each window has k numbers?
Need a nudge? A hint rules out a wrong answer.

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]

Watching a variable window

Longest substring with no repeated letters in "abcabcbb". The set holds what is inside the window.

Variable window
a
0
↑L↑R
b
1
c
2
a
3
b
4
c
5
b
6
b
7
set = {a}best = 1

Start with just a.

1/5

Try it

Run this, then change k and run it again.

Python
def max_sum(nums, k): window = sum(nums[:k]) best = window for right in range(k, len(nums)): window += nums[right] - nums[right - k] best = max(best, window) return best print(max_sum([2, 1, 5, 1, 3, 2], 3))print(max_sum([2, 1, 5, 1, 3, 2], 2))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

nums = [4, 2, 1, 7, 8]
k = 2
window = nums[0] + nums[1]
window += nums[2] - nums[0]
print(window)
Need a nudge? Hints walk you through it.
Put it in order3 steps

Put the variable-window loop body in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Spot the pattern

Match the pairs0/4 matched

Which problems are sliding windows?

Choose an item, then its match on the other side.

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).

Python
def check_inclusion(p, s): if len(p) > len(s): return False need = [0] * 26 win = [0] * 26 for ch in p: need[ord(ch) - 97] += 1 for i, ch in enumerate(s): win[ord(ch) - 97] += 1 # letter enters on the right if i >= len(p): win[ord(s[i - len(p)]) - 97] -= 1 # letter leaves on the left if win == need: return True return False assert check_inclusion("ab", "eidbaooo") is Trueassert check_inclusion("ab", "eidboaoo") is Falseassert check_inclusion("adc", "dcda") is Trueprint(check_inclusion("ab", "eidbaooo"))
Output
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 in t, and required = 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).

Minimum window for t = ABC
A
0
↑L
D
1
O
2
B
3
E
4
C
5
↑R
O
6
D
7
E
8
B
9
A
10
N
11
C
12
have = 3/3best = ADOBEC

Grow until all of A, B and C are covered. At R = 5 the window ADOBEC is valid. Record length 6.

1/5
Python
from collections import Counter, defaultdict def min_window(s, t): need = Counter(t) required = len(need) window = defaultdict(int) have = 0 best = (float("inf"), 0, 0) left = 0 for right, ch in enumerate(s): window[ch] += 1 if ch in need and window[ch] == need[ch]: have += 1 # this character is now satisfied while have == required: # valid: try to make it shorter if right - left + 1 < best[0]: best = (right - left + 1, left, right + 1) out = s[left] window[out] -= 1 if out in need and window[out] < need[out]: have -= 1 # just broke coverage left += 1 return s[best[1]:best[2]] if best[0] != float("inf") else "" assert min_window("a", "aa") == ""assert min_window("aa", "aa") == "aa"assert min_window("ab", "b") == "b"print(min_window("ADOBECODEBANC", "ABC"))
Output
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.

Python
from collections import defaultdict def character_replacement(s, k): counts = defaultdict(int) left = max_freq = best = 0 for right, ch in enumerate(s): counts[ch] += 1 max_freq = max(max_freq, counts[ch]) # never decreased if (right - left + 1) - max_freq > k: # if, not while counts[s[left]] -= 1 left += 1 best = max(best, right - left + 1) return best assert character_replacement("ABAB", 2) == 4assert character_replacement("A", 0) == 1print(character_replacement("AABABBA", 1))
Output
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.

Python
from collections import defaultdict def at_most(nums, k): counts = defaultdict(int) left = total = 0 for right, x in enumerate(nums): counts[x] += 1 while len(counts) > k: counts[nums[left]] -= 1 if counts[nums[left]] == 0: del counts[nums[left]] # keep len(counts) honest left += 1 total += right - left + 1 # every start in [left, right] works return total def exactly(nums, k): return at_most(nums, k) - at_most(nums, k - 1) assert exactly([1, 2, 1, 3, 4], 3) == 3print(at_most([1, 2, 1, 2, 3], 2), at_most([1, 2, 1, 2, 3], 1), exactly([1, 2, 1, 2, 3], 2))
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.
Quick check
Why does counting subarrays with exactly K distinct values use atMost(K) - atMost(K - 1) instead of one window?
Need a nudge? A hint rules out a wrong answer.

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 if instead of while. One step left is not always enough. Keep shrinking until the window is valid again.
  • Recording the answer before repairing the window. Update best only after the inner loop, when you know the window obeys the rule.
  • Off-by-one on the width. A window from left to right inclusive holds right - left + 1 items.
  • 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).
Quick check
Why does the shrinking trick break for shortest subarray with sum at least k, when the array has negative numbers?
Need a nudge? A hint rules out a wrong answer.

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.

ChallengeEasy

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  →  -1

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
def max_sum(nums: list[int], k: int) -> int: # Build the first window, then slide it one step at a time. pass
ChallengeMedium

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^4
  • s consists of English letters, digits, symbols and spaces.
def length_of_longest_substring(s: str) -> int: pass
Key terms
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: need holds required counts, have counts 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.
Interview pattern: Sliding Window32 problemsSpot it: Longest / shortest contiguous subarray or substring with a rule