12/32
Part 3 of 6 · A growing windowLearn and do

The same loop works whenever a broken window stays broken as it grows

Every variable window has this shape:

  1. Add the entry at right.
  2. While the window breaks the rule, remove the entry at left and move left forward.
  3. Now the window is valid. Record it.

Only the state changes with the rule:

  • No key twice: a set, or a dict of last positions to jump.
  • At most two different clients: a Counter. Shrink while len(counts) > 2, and delete keys at 0 as before.
  • Total at most a budget, with no negative numbers: a running sum. Shrink while it's over budget.

It works because of one property. Once a window breaks the rule, every longer window with the same left end breaks it too. Hold left at 0 on the log from before, and let right grow:

left stays at 0 while right grows
01234
u3u7
no repeat
u3u7u3
u3 twice
u3u7u3u1
u3 still twice
u3u7u3u1u9
u3 still twice

A stretch with a repeat keeps it when it grows. So once [left, right] breaks the rule, no window that starts at left can be the answer, and left can move on for good. The follow-ups at the end of this lesson come back to what happens when that property fails.

Now change the rule to at most two different clients. Write longest_two with the same three steps and a Counter of the window.