Python 3D Academyবাংলা

When does a sliding window work?

🌍 In real life. Your mobile pack gives 6 GB, and you note how much data you use each day. What is the longest run of days that fits in the pack? Adding a day can only use more data, and dropping a day from the start can only use less, because no day uses a negative amount. So whenever your run goes over 6 GB, drop days from its start; whenever it fits, try adding the next day.

That one fact, "growing only makes it worse, shrinking only makes it better", is exactly what makes a sliding window safe.

The idea in one sentence: a grow-and-shrink window finds the answer whenever the rule is monotone: if a window breaks the rule, every bigger window around it breaks it too, and if a window keeps it, every smaller window inside it keeps it too.

Its words:

  • monotone rule: a rule that, once a window breaks it, stays broken as the window grows, and once kept, stays kept as it shrinks
  • at most / at least: the wordings that usually give a monotone rule
  • exactly: usually not monotone by itself; with negative numbers, a sum can come back down

Examples:

  • sum of positive numbers ≤ limit: monotone (bigger windows only add)
  • no letter twice: monotone (a bigger window only adds letters)
  • has every needed letter: monotone the other way (a bigger window only gains letters), so we shrink while it holds
  • sum exactly k with negative numbers allowed: not monotone: adding −3 can bring an "over" window back to k. Use prefix sums for that (next chapter)

Watch the window keep the data within 6 GB:

Why it is correct. When the window [l, r] goes over the limit, every window that starts at l and ends at r or later is over too (more positive numbers), so l can never be the start of a longer answer: moving l right loses nothing. When it fits, every window inside it fits, so recording its length is enough.

What it costs. As before, r moves n times and l at most n times: O(n), against n(n + 1)/2 windows for trying them all.

A test for any new problem: ask "once the window breaks the rule, does every bigger window around it break it too?" For "shortest" problems, ask it the other way round: "once the window works, does every bigger window work too?" If yes, slide; if not (negative numbers, "exactly k"…), think again.

def longest_within(nums, limit):
    l = total = best = 0
    for r, x in enumerate(nums):
        total += x                 # grow
        while total > limit:       # over: shrink
            total -= nums[l]
            l += 1
        best = max(best, r + 1 - l)
    return best

print(longest_within([2, 3, 1, 2, 4, 3], 6))
print(longest_within([7, 8], 5))   # every single day is too much
print(longest_within([3, -2, 1], 2), "<- wrong: [3, -2, 1] sums to 2")
With a negative number the window shrinks too early and misses the whole list: the rule isn't monotone any more.

Mistakes and edge cases.

  • sliding when numbers can be negative: as the example shows, the answer can be silently wrong
  • shrinking with if instead of while: one step may not bring the sum back under
  • if a single item is bigger than the limit, the window becomes empty (l = r + 1) and its length 0 is fine
  • "shortest window with sum ≥ target" is the mirror image: shrink while the sum is still big enough, recording the length before each shrink

Quiz

  1. What does this print?

    nums, limit = [4, 1, 1, 3], 5
    l = total = best = 0
    for r, x in enumerate(nums):
        total += x
        while total > limit:
            total -= nums[l]
            l += 1
        best = max(best, r + 1 - l)
    print(best)
  2. Which rule can a grow-and-shrink window NOT handle?

    • Sum exactly 0, when numbers can be negative
    • Sum of positive numbers at most 10
    • No letter appears twice
  3. What question tells you whether a sliding window is safe?

    • Once a window breaks the rule, does every bigger window around it break it too?
    • Is the list sorted?
    • Is the list shorter than 100?
  4. What does this print?

    nums, limit = [7, 8], 5
    l = total = best = 0
    for r, x in enumerate(nums):
        total += x
        while total > limit:
            total -= nums[l]
            l += 1
        best = max(best, r + 1 - l)
    print(best, l)
  5. longest_within([1, 5, 1], 2) should be 1, but this answers 2: it counts [5, 1] as fitting. Which line is wrong?

    def longest_within(nums, limit):
        l = total = best = 0
        for r, x in enumerate(nums):
            total += x
            while total > limit:
                total -= x
                l += 1
            best = max(best, r + 1 - l)
        return best

Coding tasks

  1. Write longest_within(nums, limit) in O(n) for a list of positive numbers: the length of the longest stretch whose sum is at most limit.

  2. Write shortest_reaching(nums, target) in O(n) for a list of positive numbers: the length of the shortest stretch whose sum is at least target, or 0 if there is none.