Sliding window
Keep a contiguous window over an array or string and update its state as the edges move; each element enters and leaves once, so subarray and substring scans drop from O(n²) to O(n).
How it works
- Keep
left,rightand a small state (sum, counts) updated in O(1) per move. - Fixed size k: add the entering element, remove the one k steps back.
- Variable size: always expand right; shrink left while the window breaks the rule.
- Record the answer when valid: the longest after shrinking, the shortest before each shrink.
- Needs monotonic validity; negative numbers break sum windows, so switch to prefix sums.
Check yourself
Answer to mark it learned; your answers aren't scored.
Shortest subarray with sum ≥ target; all values are positive. Your window just became valid. What next?
Go deeper
Solve it in Python 10
- Best total over k consecutive dayseasy
- A repeat within k positionseasy
- Every place an anagram startsmedium
- Count runs with a product below kmedium
- Longest run without repeatsmedium
- Longest single-letter run with k editsmedium
- Most points from the ends of a rowmedium
- Shortest run of positives reaching a totalmedium
- Count runs with exactly k distinct valueshard
- Smallest window covering every needed characterhard
Full explanation
A window is a contiguous range a[left..right] plus a small state (sum, counts, distinct characters) that you update in O(1) as the edges move, instead of recomputing every subarray.
- Fixed size k: add
a[right], removea[right − k]. Max sum of k consecutive elements, moving averages, finding anagrams of a pattern in a string. - Variable size: expand
rightevery step; while the window breaks the rule, shrinkleft. Record the answer where the window is valid: longest substring without repeats, minimum window containing a pattern, shortest subarray with sum ≥ target.
Both edges only move forward, so each element enters and leaves at most once: O(n).
It only works when validity is monotonic: growing an invalid window keeps it invalid, and shrinking is what fixes it. Negative numbers break that for sums; use prefix sums with Hash maps, sets and prefix sums instead. For the max or min of each window, keep a Stacks and monotonic stacks-style deque.
Code Variable and fixed window templates
def longest_unique_substring(s: str) -> int:
count: dict[str, int] = {}
left = best = 0
for right, ch in enumerate(s):
count[ch] = count.get(ch, 0) + 1
while count[ch] > 1: # invalid: shrink until the repeat leaves
count[s[left]] -= 1
left += 1
best = max(best, right - left + 1) # longest: record after shrinking
return best
def shortest_subarray_at_least(target: int, a: list[int]) -> int:
# Values must be non-negative, or shrinking could raise the sum
left = total = 0
best = float("inf")
for right, x in enumerate(a):
total += x
while total >= target: # shortest: record while valid, then shrink
best = min(best, right - left + 1)
total -= a[left]
left += 1
return 0 if best == float("inf") else best
def max_sum_k(a: list[int], k: int) -> int:
window = best = sum(a[:k])
for right in range(k, len(a)):
window += a[right] - a[right - k] # one in, one out
best = max(best, window)
return bestReal example
Longest substring without repeating characters on "abcabcbb": the window grows to abc (3). The second a makes it invalid, so left moves past the first a → bca, still 3. It never beats 3, so the answer is 3: right moves 8 times and left at most 8, instead of testing all 36 substrings.
Trade-offs +3 · −3
+ You gain
- O(n) time with O(1) or O(alphabet) extra space.
- One template covers fixed and variable windows over arrays and strings.
- Works on streams: you only keep the window, not the whole input.
− You pay
- Only for contiguous ranges with a monotonic validity rule.
- Sum constraints break with negative numbers.
- The shrink condition and where to record the answer are easy to get wrong.
Use it when
"Longest, shortest or number of contiguous subarrays or substrings such that…", fixed-length windows (moving sums, averages, anagram search), and counts over a stream.
Avoid it when
Non-contiguous choices (subsequences: think DP), sum targets with negative numbers (prefix sums with a hash map), or rules where shrinking doesn't restore validity.
Numbers to know 4
- O(n) time:
rightmoves n times andleftat most n times in total. - Space O(k) for window counts, k = alphabet size or distinct values (26 for lowercase letters).
- Brute force: O(n²) windows, O(n³) if each is rescanned.
- Sliding-window minimum with a monotonic deque: O(n) total, versus O(n·k) rescanning each window.
Common pitfalls 4
- Recording the answer before shrinking, so invalid windows count.
ifinstead ofwhileto shrink: one step may not restore validity.- Jumping
leftwith a last-seen map withoutmax(left, last[ch] + 1): the window moves backward. - Applying it to sums with negative numbers: shrinking can raise the sum.
Interview questions 2
Answer out loud first, then reveal.
How do you spot a sliding window problem?Show answer
The question asks for the longest, shortest or number of contiguous subarrays or substrings that meet a condition, and brute force would examine all O(n²) of them. Then I check monotonicity: if a window is invalid, does every larger window containing it stay invalid? If yes, a variable window gives O(n). If the size is given, it's a fixed window. If not monotonic, say with negative numbers, I switch to prefix sums.
Count subarrays with at most K distinct values. Now exactly K.Show answer
At most K is a direct variable window: for each right, shrink while distinct > K, then add right − left + 1, the number of valid subarrays ending at right. Exactly K isn't monotonic, so I use exactly(K) = atMost(K) − atMost(K − 1). Two O(n) passes and O(K) space for the counts.