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 variantsFixed window
0 of 10 solved- Best k-day streakUp nextEasyDecode Best k-day streak
- Maximum Average Subarray IEssentialsDeep diveEasyDecode Maximum Average Subarray I
- Minimum Recolors to Get K Consecutive Black BlocksEasyDecode Minimum Recolors to Get K Consecutive Black Blocks
- Find the Index of the First Occurrence in a StringSprintDeep diveEasyDecode Find the Index of the First Occurrence in a String
- Maximum Number of Vowels in a Substring of Given LengthEssentialsDeep diveMediumDecode Maximum Number of Vowels in a Substring of Given Length
- K Radius Subarray AveragesDeep diveMediumDecode K Radius Subarray Averages
- Grumpy Bookstore OwnerDeep diveMediumDecode Grumpy Bookstore Owner
- Maximum Points You Can Obtain from CardsDeep diveMediumDecode Maximum Points You Can Obtain from Cards
- Minimum Swaps to Group All 1's Together IIDeep diveMediumDecode Minimum Swaps to Group All 1's Together II
- Sliding Window MaximumDeep diveHardDecode Sliding Window Maximum
Variable window
0 of 7 solved- Longest Substring Without Repeating CharactersSprintDeep diveMediumDecode Longest Substring Without Repeating Characters
- Max Consecutive Ones IIIEssentialsDeep diveMediumDecode Max Consecutive Ones III
- Longest Subarray of 1's After Deleting One ElementEssentialsDeep diveMediumDecode Longest Subarray of 1's After Deleting One Element
- Minimum Size Subarray SumSprintDeep diveMediumDecode Minimum Size Subarray Sum
- Frequency of the Most Frequent ElementMediumDecode Frequency of the Most Frequent Element
- Get Equal Substrings Within BudgetMediumDecode Get Equal Substrings Within Budget
- Longest Nice SubarrayMediumDecode Longest Nice Subarray
Jumping window
0 of 3 solvedWindow with counts
0 of 9 solved- Contains Duplicate IISprintDeep diveEasyDecode Contains Duplicate II
- Longest Repeating Character ReplacementDeep diveMediumDecode Longest Repeating Character Replacement
- Permutation in StringDeep diveMediumDecode Permutation in String
- Find All Anagrams in a StringDeep diveMediumDecode Find All Anagrams in a String
- Maximum Sum of Distinct Subarrays With Length KMediumDecode Maximum Sum of Distinct Subarrays With Length K
- Fruit Into BasketsMediumDecode Fruit Into Baskets
- Longest Substring with At Most K Distinct CharactersMediumDecode Longest Substring with At Most K Distinct Characters
- Minimum Window SubstringSprintDeep diveHardDecode Minimum Window Substring
- Substring with Concatenation of All WordsSprintDeep diveHardDecode Substring with Concatenation of All Words
Counting subarrays
0 of 3 solvedPattern 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.
Grow until the sum reaches 7: 2 + 3 + 1 + 2 = 8. The window is valid, so record its width, 4.
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).
while loop inside a for loop. Why is it still O(n)?How to recognise it
Wording clues
| Phrase in the prompt | What 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
| Constraint | What it suggests |
|---|---|
n up to 10^5 or 10^6 | O(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 negative | A sum window can skip answers. Reach for prefix sums and a hash map (or a monotonic deque) instead. |
| Lowercase letters only | Counts fit in a 26-slot array, so comparing two windows is O(1). |
k can be 0 or larger than n | Make 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 numberk. - 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 allowed | Prefix sums plus a hash map |
| Pairs in a sorted array that meet a target | Two pointers from both ends |
| Longest increasing subsequence (gaps allowed) | Dynamic programming or binary search |
| Next greater element for every index | Monotonic stack |
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.
First window abc has 1 vowel.
Press Run (⌘ Enter) to see what happens.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.
One zero so far, within budget. Width 4.
Press Run (⌘ Enter) to see what happens.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.
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)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.
Window [1]. One distinct value.
Press Run (⌘ Enter) to see what happens.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.
[10] is valid: add 1.
Press Run (⌘ Enter) to see what happens.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.
Start buying at 7.
Press Run (⌘ Enter) to see what happens.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 each problem to the sub-pattern you would reach for first.
Put the steps of decoding a window problem in order.
- Tap the steps below in the right order.
Traps
ifinstead ofwhilewhen 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]holdsright - left + 1elements. In Longest Subarray of 1's After Deleting One Element, the forced deletion makes itright - left. - Leaving zero-count keys in the map. If you do not delete them,
len(counts)overstates the number of distinct values. - Starting
bestat 0 when values can be negative. Start from the first window's value instead. - Jumping
leftbackwards. With a last-index map, only jump when the old index is at or afterleft. - Negative numbers in sum problems. Shrinking assumes removing an element cannot help. Negatives break that.
- Mutating the input. Sorting
numsin 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.
- 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.