Skip to content

Sliding Window

Reach for it when the problem says

  • Longest / shortest contiguous subarray or substring with a rule
Solved
0/32Solved
Problems
32Problems
Variants
5Variants

Problems

5 variants

Fixed window

0 of 10 solved

Variable window

0 of 7 solved

Jumping window

0 of 3 solved

Window with counts

0 of 9 solved

Counting subarrays

0 of 3 solved

Pattern guide

Sliding window problems are among the most common interview questions because the brute force is obvious (check every range, O(n²)) and the fix is a clean single pass. If you can recognise the shape in the first minute and name the sub-pattern, most of these problems come down to writing a short loop correctly.

What it is

A window is a contiguous range [left, right] of an array or string. Instead of looking at every range from scratch, you keep one window and move its edges forward. Each move changes the window by one element, so you update a small piece of state (a sum, a count, a set) in O(1) instead of recomputing it.

Here is a variable window finding the shortest subarray with sum at least 7 in [2, 3, 1, 2, 4, 3]. Watch how right only ever grows the window and left only ever shrinks it.

Shortest subarray with sum at least 7
2
0
↑L
3
1
1
2
2
3
↑R
4
4
3
5
sum = 8best = 4

Grow until the sum reaches 7: 2 + 3 + 1 + 2 = 8. The window is valid, so record its width, 4.

1/5

The reason this is O(n) and not O(n²) is that neither pointer ever moves backwards. Each element is added once and removed at most once, so the inner while loop does about n steps in total across the whole scan, not n steps per outer iteration. People call that amortized O(n).

Quick check
A variable window has a while loop inside a for loop. Why is it still O(n)?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it implies
"contiguous", "substring", "subarray", "consecutive"The answer is a range of neighbours. Windows only work on ranges.
"of length k", "every k consecutive", "size k"Fixed window: the edges stay exactly k apart.
"longest ... such that", "maximum length"Variable window that grows and shrinks only when forced.
"shortest ... such that", "minimum length"Variable window that shrinks while it is still valid.
"at most k distinct", "at most k changes", "at most k zeros"A budget. Count the budget inside the window and shrink when it is exceeded.
"anagram", "permutation of", "contains all characters of"Compare letter counts, so keep a count map for the window.
"number of subarrays", "count substrings"Counting: add a whole batch of windows at each step.
"exactly k"Rewrite as at most k minus at most k - 1.

Constraint clues

ConstraintWhat it suggests
n up to 10^5 or 10^6O(n²) is too slow. A window gives O(n).
Values are positive (1 <= nums[i])Sums and products grow as the window grows, so shrinking is safe.
Values can be negativeA sum window can skip answers. Reach for prefix sums and a hash map (or a monotonic deque) instead.
Lowercase letters onlyCounts fit in a 26-slot array, so comparing two windows is O(1).
k can be 0 or larger than nMake sure the window can be empty, and that a huge budget gives the whole input.

Input and output shape clues

  • Input: one array or string, sometimes with a second string of letters to match (t, p, s1), and a number k.
  • Output: a single length, sum or count, or a list of start indices. Almost never "all the subarrays themselves".
  • Order matters: you cannot sort the input without destroying the answer (the one big exception is Frequency of the Most Frequent Element, where sorting is the first step that creates contiguity).

Looks like it but isn't

It looks like a window, but...Use instead
The chosen elements need not be adjacent ("pick any k numbers")Sorting or a heap
Sum exactly k with negative numbers allowedPrefix sums plus a hash map
Pairs in a sorted array that meet a targetTwo pointers from both ends
Longest increasing subsequence (gaps allowed)Dynamic programming or binary search
Next greater element for every indexMonotonic stack
Quick check
Which input breaks the shrink-while-valid window for 'shortest subarray with sum at least k'?
Need a nudge? A hint rules out a wrong answer.

The sub-patterns

Fixed window

When it applies: the window length is given (k, minutes, 2k + 1, len(p)) or forced by the problem (the cards you leave, the block where all the 1s end up). Build the first window, then slide: one element in on the right, one out on the left.

Most vowels in any 3 letters
a
0
↑L
b
1
c
2
↑R
i
3
i
4
i
5
d
6
vowels = 1best = 1

First window abc has 1 vowel.

1/4
Python
def best_window_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(best_window_sum([2, 1, 5, 1, 3, 2], 3))print(best_window_sum([-3, -1, -2], 1))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space for sums and counts.

Best-known problems: Maximum Average Subarray I, Maximum Number of Vowels in a Substring of Given Length, Maximum Points You Can Obtain from Cards, Sliding Window Maximum.

When the window tracks a maximum: the monotonic deque

A sum can be undone by subtraction; a maximum cannot. For Sliding Window Maximum, keep a deque of indices whose values decrease from front to back. Before pushing a new index, pop every smaller-or-equal value off the back (they can never be the max again, because the new value is bigger and lives longer). Pop the front when it slides out of the window. The front is always the current max, and every index is pushed and popped once, so it stays O(n).

Variable window

When it applies: "longest" or "shortest" contiguous range where a rule holds, and the rule is monotonic: if a window breaks it, every bigger window containing it also breaks it. Grow right every step; shrink left with a while loop until the rule holds again.

Longest run of 1s with at most k = 1 flip
1
0
↑L
1
1
0
2
1
3
↑R
0
4
1
5
1
6
zeros = 1best = 4

One zero so far, within budget. Width 4.

1/4
Python
def longest_ones(nums, k): left = zeros = best = 0 for right, x in enumerate(nums): if x == 0: zeros += 1 while zeros > k: # repair the window if nums[left] == 0: zeros -= 1 left += 1 best = max(best, right - left + 1) # record a valid window return best print(longest_ones([1, 1, 0, 1, 0, 1, 1], 1))print(longest_ones([0, 0, 0], 0))
Output
Press Run (⌘ Enter) to see what happens.

For shortest problems, flip where you record: record inside the while loop, while the window is still valid, then shrink.

Complexity: O(n) time, O(1) space.

Best-known problems: Longest Substring Without Repeating Characters, Max Consecutive Ones III, Minimum Size Subarray Sum, Frequency of the Most Frequent Element.

Predict the outputPython

What does this print?

nums = [1, 4, 4]
target = 4
left = total = 0
best = len(nums) + 1
for right, x in enumerate(nums):
  total += x
  while total >= target:
      best = min(best, right - left + 1)
      total -= nums[left]
      left += 1
print(best)
Need a nudge? Hints walk you through it.

Window with counts

When it applies: the rule depends on how many of each value sit in the window: anagrams, permutations, "contains every character of t", "at most k distinct", "all elements distinct". Keep a hash map (or a 26-slot array for lowercase letters) from value to count. Delete keys that reach zero so the map's size equals the number of distinct values.

At most 2 distinct in [1, 2, 1, 3]

puthash("1") % 8 = 1

  1. 0empty
  2. 1"1":1
  3. 2empty
  4. 3empty
  5. 4empty
  6. 5empty
  7. 6empty
  8. 7empty

Window [1]. One distinct value.

1/4
Python
def longest_k_distinct(s, k): counts = {} left = best = 0 for right, ch in enumerate(s): counts[ch] = counts.get(ch, 0) + 1 while len(counts) > k: counts[s[left]] -= 1 if counts[s[left]] == 0: del counts[s[left]] left += 1 best = max(best, right - left + 1) return best print(longest_k_distinct("eceba", 2))print(longest_k_distinct("abaccc", 2))
Output
Press Run (⌘ Enter) to see what happens.

Fixed-length anagram problems use the same counts on a fixed window: count p once, slide a window of len(p), and compare the two 26-slot arrays after each step. Minimum Window Substring adds one more idea, a single missing counter, so checking "does the window cover t?" is O(1).

Complexity: O(n) time (O(n + m) with a second string), O(alphabet) or O(k) space.

Best-known problems: Permutation in String, Find All Anagrams in a String, Longest Repeating Character Replacement, Minimum Window Substring, Fruit Into Baskets.

Counting subarrays

When it applies: the question is "how many subarrays..." rather than "how long". The trick: once the window [left, right] is valid for an at-most rule, every window ending at right that starts inside it is also valid. That is right - left + 1 subarrays in one addition. For an at-least rule, flip it: shrink until invalid, and the left starts you cut off were the valid ones.

Subarrays with product below 100
10
0
↑L↑R
5
1
2
2
6
3
product = 10count = 1

[10] is valid: add 1.

1/4
Python
def count_at_most_k_distinct(nums, k): counts = {} left = total = 0 for right, x in enumerate(nums): counts[x] = counts.get(x, 0) + 1 while len(counts) > k: counts[nums[left]] -= 1 if counts[nums[left]] == 0: del counts[nums[left]] left += 1 total += right - left + 1 return total def exactly_k(nums, k): return count_at_most_k_distinct(nums, k) - count_at_most_k_distinct(nums, k - 1) print(exactly_k([1, 2, 1, 2, 3], 2))
Output
Press Run (⌘ Enter) to see what happens.

That last line is the at most K trick: "exactly k" is hard for one window, because the valid starts sit in a middle range, but exactly(k) = at_most(k) - at_most(k - 1) turns it into two easy windows.

Complexity: O(n) time, O(1) to O(n) space for the counts.

Best-known problems: Subarray Product Less Than K, Number of Substrings Containing All Three Characters, Subarrays with K Different Integers.

Jumping window

When it applies: when the rule breaks, you already know exactly where the next valid window must start, so left jumps there in one move instead of creeping. Typical signals: you can store the last index of each value, or validity depends only on the last one or two elements.

Best time to buy and sell: the left edge jumps to each new low
7
0
↑buy↑sell
1
1
5
2
3
3
6
4
4
5
profit = 0

Start buying at 7.

1/4
Python
def longest_unique(s): last = {} left = best = 0 for right, ch in enumerate(s): if ch in last and last[ch] >= left: left = last[ch] + 1 # jump past the old copy last[ch] = right best = max(best, right - left + 1) return best print(longest_unique("abcabcbb"))print(longest_unique("abba"))
Output
Press Run (⌘ Enter) to see what happens.

The last[ch] >= left check matters: in "abba", the final a was last seen at index 0, which is already behind left = 2. Jumping to 1 would move the window backwards.

Complexity: O(n) time, O(1) or O(distinct values) space.

Best-known problems: Best Time to Buy and Sell Stock, Longest Turbulent Subarray, Maximum Erasure Value.

Decision checklist

Match the pairs0/5 matched

Match each problem to the sub-pattern you would reach for first.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps of decoding a window problem in order.

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

Traps

  • if instead of while when shrinking. One step left is not always enough. Keep shrinking until the window is valid again.
  • Recording at the wrong moment. For "longest", record after the repair loop. For "shortest", record inside it, before each shrink.
  • Off-by-one widths. An inclusive window [left, right] holds right - left + 1 elements. In Longest Subarray of 1's After Deleting One Element, the forced deletion makes it right - left.
  • Leaving zero-count keys in the map. If you do not delete them, len(counts) overstates the number of distinct values.
  • Starting best at 0 when values can be negative. Start from the first window's value instead.
  • Jumping left backwards. With a last-index map, only jump when the old index is at or after left.
  • Negative numbers in sum problems. Shrinking assumes removing an element cannot help. Negatives break that.
  • Mutating the input. Sorting nums in place (Frequency of the Most Frequent Element) surprises callers. Sort a copy.

Always test: the empty or single-element input, k = 0, k equal to or bigger than n, all-equal values, and a case where the best window is at the very end.

Quick check
In an 'at most k distinct' window you decrement counts but never delete keys that hit 0. What goes wrong?
Need a nudge? A hint rules out a wrong answer.
Key terms
window
A contiguous range [left, right] whose state you update incrementally as its edges move.
fixed window
A window whose length never changes. Each step adds one element and removes one.
variable window
Grows on the right every step and shrinks on the left while a monotonic rule is broken.
at most K trick
Count subarrays with exactly k of something as at_most(k) minus at_most(k - 1).
monotonic deque
A deque of indices kept in decreasing (or increasing) value order, giving the window max (or min) in O(1).
amortized O(n)
Each pointer only moves forward, so the total work across all inner loops is linear.