Learn / Arrays

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

rightvaluezerosactionwindowbest
110grow0 to 12
201grow0 to 23
302shrink past index 23 to 33
611grow3 to 64
702shrink past index 34 to 74
811grow4 to 85

Common mistakes

  • Using if instead of while to shrink, so one step of left is 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 of nums[right].

Problems

0 of 12 solved

Check yourself

Longest window with at most 2 zeros. The window has just reached 3 zeros. What happens next?

Both edges only move forwards. Why is the scan O(n) even though there is a loop inside a loop?

How do you count the subarrays whose sum is exactly k, using only windows, when all values are 0 or 1?

Why does a sliding window fail for "longest subarray with sum k" when the array has negative numbers?