Python coding

Longest single-letter run with k edits

Given a string s of uppercase letters and an integer k, you may change at most k characters of s, each to any letter you like. Return the length of the longest contiguous substring that can end up made of a single repeated letter.

s may be empty and k >= 0. Aim for one pass over s.

Besides the tests, one large input (a 3,000-letter string) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • longest_uniform("BAAABCB", 1) → 4
  • longest_uniform("XYXY", 2) → 4
  • longest_uniform("AABAA", 1) → 5
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Variable-size sliding window: grow it to the right and count each letter it contains.

Hint 2

The cheapest way to make a window uniform is to keep its most common letter. That takes window length − highest count edits; shrink from the left while it exceeds k.

Hint 3

Do not fix the target letter in advance: take the highest count of the current window. The answer never exceeds len(s).

Solution and why it works
pythonO(n·A), A = alphabet size (26) · O(A)
def longest_uniform(s: str, k: int) -> int:
    count = {}
    left = best = 0
    for right, ch in enumerate(s):
        count[ch] = count.get(ch, 0) + 1
        # Keep the most common letter; every other character in the window costs one edit.
        while (right - left + 1) - max(count.values()) > k:
            count[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

A window can become one letter by keeping its most common letter and editing the rest, so it is valid when length − highest count <= k. Growing an invalid window never fixes it, so expand right and shrink left while the rule breaks. The trap is tying the window to one letter (the newest, or the most common in the whole string): the best letter changes as the window moves. Extending the longest existing run by k fails too: "AABAA" with k = 1 gives 5.

Related lab: Sliding window, step by step