Sliding window: variable size
A window whose edges move independently. The right edge grows it one element at a time, and the left edge shrinks it as soon as a rule breaks (for the longest answer) or as long as the rule still holds (for the shortest). Both edges only move forwards, so the whole scan is O(n).
How to recognise it
- The longest or shortest subarray or substring that satisfies a rule.
- The rule is about the window's contents, such as a sum, a count of zeros, or the number of distinct characters.
- Adding an element can only make the rule harder (or easier) to satisfy, never both. Values are non-negative, for example.
- Count the subarrays with exactly k of something, which becomes at most k minus at most k - 1.
The idea in one picture
Think of a caterpillar crawling along the array. Its head (right) always moves forwards and eats one new element.
When the body breaks the rule (too many zeros, too many kinds of fruit, a repeated letter), the tail (left) moves
forwards until the rule holds again. The tail never overtakes the head, and neither ever moves back. So the caterpillar
crosses the array once, and every window that could be the answer gets checked.
Two templates
Longest window that satisfies the rule: grow, then shrink while the rule is broken, then record.
left = 0, best = 0
for right from 0 to n - 1:
add nums[right] to the window
while the window breaks the rule:
remove nums[left] from the window
left = left + 1
best = max(best, right - left + 1)
Shortest window that satisfies the rule: grow, then record and shrink while the rule still holds.
left = 0, best = infinity
for right from 0 to n - 1:
add nums[right] to the window
while the window satisfies the rule:
best = min(best, right - left + 1)
remove nums[left] from the window
left = left + 1
When it works
The rule must be monotonic: if a window breaks it, every bigger window that contains it breaks it too (or, for the shortest version, if a window satisfies it, every bigger window does). "At most k zeros", "at most two kinds" and "sum of non-negative values above x" are monotonic. "Sum exactly k with negative values" is not, and needs prefix sums.
Counting with "at most"
To count windows with exactly k of something, count windows with at most k and subtract those with at most
k - 1. Counting "at most k" is easy: once the window ending at right is as long as allowed, every start from left to
right works, which is right - left + 1 subarrays.
A guided example: longest stretch of [1, 1, 0, 0, 1, 1, 1, 0, 1] with at most one 0
| right | value | zeros | action | window | best |
|---|---|---|---|---|---|
| 1 | 1 | 0 | grow | 0 to 1 | 2 |
| 2 | 0 | 1 | grow | 0 to 2 | 3 |
| 3 | 0 | 2 | shrink past index 2 | 3 to 3 | 3 |
| 6 | 1 | 1 | grow | 3 to 6 | 4 |
| 7 | 0 | 2 | shrink past index 3 | 4 to 7 | 4 |
| 8 | 1 | 1 | grow | 4 to 8 | 5 |
Common mistakes
- Using
ifinstead ofwhileto shrink, so one step ofleftis not enough and the window stays broken. - Recording the answer at the wrong moment: after shrinking for the longest window, before shrinking for the shortest.
- Applying a window to a rule that is not monotonic, such as sums with negative values.
- Forgetting to undo exactly what was added: remove the count of
nums[left], not ofnums[right].
Problems
- Longest Substring Without Repeating Charactersmediumguide ready
- Max Consecutive Ones IIImediumguide ready
- Fruit Into Basketsmediumguide ready
- Longest Substring with At Most K Distinct Charactersmediumguide ready
- Longest Repeating Character Replacementmediumguide ready
- Number of Substrings Containing All Three Charactersmediumguide ready
- Binary Subarrays With Summediumguide ready
- Count Number of Nice Subarraysmediumguide ready
- Smallest Subarray with sum greater than a given valuemediumguide ready
- Write a program to find the smallest window that contains all characters of string itselfmediumguide ready
- Minimum removals from array to make max –min <= Kmediumguide ready
- Minimum Window Substringhardguide ready