download

Longest run after k replacements: why can the max count stay stale?

Algorithms~20 minReviewed 1 Nov 2026Free · No sign-in

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).

"PYTHON"
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.

"CODE · PYTHON"
def longest_run(tiles, k):
    ...
Show hints (3)
  1. "COST OF A WINDOW"

    In one window, which color should you keep? The most common one. So a window needs size - top_count repaints, where top_count is how often its most common color appears.

  2. "GROW OR SLIDE"

    Add one tile on the right each step. If the window now needs more than k repaints, move the left edge one step. The window never shrinks, so its size is the best length so far.

  3. "THE STALE COUNT"

    max_count is 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.

"SOLUTION · PYTHON"
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))
"OUTPUT"
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.

rightaddsmax_countwindowreal topaction
0A1A1grow
1A2AA2grow
2B2AAB2grow
3A3AABA3grow
4B3ABAB2slide
5B3BABB3slide
6A3ABBA2slide

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" with k = 1 it ends as ABBA, which needs 2 repaints. Only its length is right.
  • Sliding when the window needs >= k repaints instead of > k. A window that needs exactly k repaints is fine. The example returns 2 instead of 4.
  • Counting repaints with the color just added instead of the most common one. On "AAB" with k = 1, adding B looks like 2 repaints, so you get 2 instead of 3.
  • Forgetting counts[tiles[left]] -= 1 when the left edge moves. Tiles outside the window still count, max_count rises 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 left and right each time the window grows. A window that just grew needs at most k repaints. For "AABABBA" with k = 1 that gives AABA, positions 0 to 3.
  • "Can you write it so that every window is valid?" Yes. Shrink with a while loop, and recompute the top count with max(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 →

Original OfferVibe question. Topic idea from Coding Interview Patterns (Alex Xu and Shaun Gunawardane, 2024); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.