Longest run after k replacements: why can the max count stay stale?
Question
A row of tiles is painted in colors, written as uppercase letters. You may repaint at most k tiles. Return the length of the longest stretch of neighbouring tiles that can end up all one color. Aim for O(n).
longest_run("AABABBA", 1) # 4: repaint "AABA" to "AAAA" longest_run("ABC", 0) # 1
The usual solution keeps a max_count that never goes down, even when tiles leave the window. Explain why it still returns the right length.
def longest_run(tiles, k): ...
Show hints (3)
- "COST OF A WINDOW"
In one window, which color should you keep? The most common one. So a window needs
size - top_countrepaints, wheretop_countis how often its most common color appears. - "GROW OR SLIDE"
Add one tile on the right each step. If the window now needs more than
krepaints, move the left edge one step. The window never shrinks, so its size is the best length so far. - "THE STALE COUNT"
max_countis never below the real top count, so it only makes the loop slide less. And it was a real count once. What does each fact say about the length?
Show checked explanation
Slide a window and count its colors. It needs size - max_count repaints. When that is over k, move the left edge one step, so the window never shrinks. A stale max_count is never too low, so the window never ends up too short. It was a real count once, so the window never gets too long.
from collections import Counter def longest_run(tiles, k): counts = Counter() max_count = 0 left = 0 for right, color in enumerate(tiles): counts[color] += 1 max_count = max(max_count, counts[color]) if right - left + 1 - max_count > k: counts[tiles[left]] -= 1 left += 1 return len(tiles) - left print(longest_run("AABABBA", 1)) print(longest_run("ABC", 0)) print(longest_run("", 2))
4 1 0
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is "AABABBA" with k = 1. real top is the true count of the most common color in the window.
| right | adds | max_count | window | real top | action |
|---|---|---|---|---|---|
| 0 | A | 1 | A | 1 | grow |
| 1 | A | 2 | AA | 2 | grow |
| 2 | B | 2 | AAB | 2 | grow |
| 3 | A | 3 | AABA | 3 | grow |
| 4 | B | 3 | ABAB | 2 | slide |
| 5 | B | 3 | BABB | 3 | slide |
| 6 | A | 3 | ABBA | 2 | slide |
At step 4, AABAB needs 5 - 3 = 2 repaints, so the left edge moves. The window ABAB has a real top count of 2, but max_count stays 3. ABAB is not valid, yet its length, 4, is the answer.
Why is the length right? The window never shrinks, so its final size is its biggest size. Check it from both sides.
Never too long. The loop slides as soon as the size would pass max_count + k. And max_count was a real count once: that many tiles of one color sat in the window together. Here they are the three A's of AABA at step 3. A stretch of the current size around those tiles has at most k other tiles. So a valid stretch that long really exists.
Never too short. max_count is never below the real top count. So a stale value makes the loop slide less often, never more. Any window inside the best stretch is valid, so the loop never slides it. So while the right edge moves through the best stretch, the left edge can't pass its start. At the end, the window holds all of it. Here the left edge stays at 0 until step 3, and the window is AABA.
Lowering max_count would only add slides. Each tile enters once and leaves at most once, so the loop is O(n).
Common mistakes
- Returning the last window as the answer. For
"AABABBA"withk = 1it ends asABBA, which needs 2 repaints. Only its length is right. - Sliding when the window needs
>= krepaints instead of> k. A window that needs exactlykrepaints is fine. The example returns 2 instead of 4. - Counting repaints with the color just added instead of the most common one. On
"AAB"withk = 1, adding B looks like 2 repaints, so you get 2 instead of 3. - Forgetting
counts[tiles[left]] -= 1when the left edge moves. Tiles outside the window still count,max_countrises too early, and the example returns 5 instead of 4.
Follow-up questions
- "Return the stretch itself, not just its length." Don't use the last window. Save
leftandrighteach time the window grows. A window that just grew needs at mostkrepaints. For"AABABBA"withk = 1that givesAABA, positions 0 to 3. - "Can you write it so that every window is valid?" Yes. Shrink with a
whileloop, and recompute the top count withmax(counts.values())after each change. With 26 letters that costs up to 26 operations per step, so O(26·n). Still linear for a fixed alphabet.
What a strong answer covers
Says a window costs its size minus its top count. Explains that the window never shrinks, a stale max_count only makes it slide less, and it was a real count once. Knows the last window may not be valid.
Open in interactive practice deck →