Longest Repeating Character Replacement

MediumSliding windowLeetCode 424 ↗World 2-9
0:00 / 0:00

Change at most k letters to get the longest run of one letter. Slide a window and keep letter counts: it's fine while its length minus its most common letter's count is at most k, and the top count never needs to shrink. O(n) time.

▼

The problem

LeetCode 424 (Medium). Given a string s of uppercase English letters and an integer k, you may replace at most k characters with any other uppercase letter; return the length of the longest substring of one repeated letter you can get.

The example (illustrative, not LeetCode's): s = "AABABBBB", k = 1 → 6 (change the A in BABBBB). It replaces the original's LeetCode example AABABBA because its walkthrough shows everything the sliding window does: it grows, needs too many changes and slides, sits on a stale top count (ABAB really needs 2 while the record says 3), slides again, and then grows twice when B's count beats the record. Scene 1's BABBA with k = 1 (answer 4) is illustrative too.

The slow way shown (scene 3): check every substring; the changes it needs are its length minus its most common letter's count; n(n + 1)/2 = 36 substrings for n = 8, O(n²). The solution shown is the sliding window with letter counts and a top count that never decreases: each step adds s[right]; if length - top > k the left edge moves by one, so the window never shrinks. O(n) time, O(26) = O(1) space. The exact code on screen (CODE in src/scenes/S6.jsx):

def characterReplacement(s, k):
    count = {}
    left = top = best = 0
    for right, ch in enumerate(s):
        count[ch] = count.get(ch, 0) + 1
        top = max(top, count[ch])
        if right - left + 1 - top > k:
            count[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

Why top never has to go down (scene 5): a stale, too-high top only appears after a slide, and then the window's length is exactly top + k; it can grow only when top rises, which happens only when the letter just added really reaches that count inside the current window, so every length the window reaches is a valid one.

Checked in a throwaway script against a brute force (every substring) on 200,000 random inputs (n 0..12, alphabets of 1–4 letters, every k 0..n) and on the examples. Every value on screen comes from replaceTrace() / replay() in src/choir.jsx, which re-check themselves against a brute force and the trace when the module loads; the scenes assert the traces they draw. The example's trace (right = 0..7): top 1 2 2 3 3 3 4 5; length before a slide 1 2 3 4 5 5 5 6; slides at right = 4 and 5 (dropping A, A); best 1 2 3 4 4 4 5 6; left ends at 2; the final window BABBBB has A 1, B 5; answer 6.

TRY IT ON LEETCODE ▶

The solution

def characterReplacement(s, k):
    count = {}
    left = top = best = 0
    for right, ch in enumerate(s):
        count[ch] = count.get(ch, 0) + 1
        top = max(top, count[ch])
        if right - left + 1 - top > k:
            count[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

Transcript

Longest Repeating Character Replacement. You get a string of capital letters and a number k. You may change up to k of the letters. How long is the longest run of one repeated letter you can make?

Take A, A, B, A, B, B, B, B, with k one. Change the A in B, A, B, B, B, B, and six B's stand in a row. The answer is six.

The slow way tries every substring. Every letter except the most common one has to change, so a substring needs its length minus its top count. With n letters, that's about n squared substrings to check.

Instead, slide one window along the string and count the letters inside it. It's fine while its length minus its top count is at most k. Each step, the right edge takes in one more letter. If that needs too many changes, the left edge steps forward too, so the size holds.

Here's the subtle part: when a letter leaves, the top count never drops. A stale record can't make the window grow. It only slides along at a size that already worked. To grow, some letter's real count must beat the record. So the best length is never inflated.

In code, count each new letter and update the top count. If the length minus the top is more than k, take the left letter out and move left forward. Then keep the best length.

Let's run the example. A, A: the top count is two. B: one change, fine. A: top count three, four letters. B: five letters need two changes, so slide. Now A, B, A, B really needs two, but the record still says three. Next B: slide again. Next B: its count reaches four and beats the record, so the window grows to five. The last B makes six.

Each letter enters the window once and leaves at most once: order n time. At most twenty six counts: order one space.

Count, grow, slide when you must. That's Longest Repeating Character Replacement.