LeetCode #424 Medium

Longest Repeating Character Replacement

Longest Repeating Character Replacement is LeetCode 424 (Medium). You get a string s of uppercase letters and a number k. You may change up to k characters, each into any other uppercase letter.

  • Return the length of the longest substring that can be turned into one letter repeated.

The string can hold 100,000 characters, so checking every substring is too slow; the answer has to come from one pass.

Constraints
  • 1 <= s.length <= 10⁵
  • s consists of only uppercase English letters.
  • 0 <= k <= s.length
sliding-windowstringshashing
Open on LeetCode ↗
02

Intuition

Take any window of the string. The cheapest way to make it one letter is to keep its most common letter and change all the others. So a window needs (its length − the count of its most common letter) changes, and it is usable when that number is at most k.

  • Grow: move the right end one letter at a time, counting letters as they enter.
  • Slide: when the window needs more than k changes, move the left end one step. The window keeps its length instead of shrinking, because only a longer window could beat the best one found so far.
How to spot this pattern

A request for the longest contiguous stretch that stays within a budget, where adding letters can only raise the cost, is a two-pointer window. Max Consecutive Ones III is the same idea with only two symbols.

03

Approach

Try it first

Before reading on: for one fixed window, how many changes does it need? Then decide what to move when that number passes k. Aim for O(n) time.

1

Count the letters in the window

Keep count, how often each letter appears between left and right, and top, the highest count any letter has reached. There are only 26 letters, so count stays tiny.

2

Add the next letter

For each right, add one to count[s[right]] and raise top if that letter is now the most common. The number of changes the window needs is right - left + 1 - top.

3

Move the left end when the budget is passed

If the window needs more than k changes, take one from count[s[left]] and step left forward. One letter was just added to a window that fitted, so one step brings the length back to that earlier window's length.

4

Why `top` never has to go down

After the left end moves, top can be higher than any count still in the window. That is safe: the window only grows past the best length when some letter reaches a count above the old top, and then top is exact again. A too-high top only blocks windows that could not win.

5

Keep the longest window

After the check, set best to the larger of best and right - left + 1, and return best at the end. The window is never longer than a window that really fitted the budget.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def characterReplacement(self, s: str, k: int) -> int:
▶3 count = {}
▶4 left = top = best = 0
▶5 for right, ch in enumerate(s):
▶6 count[ch] = count.get(ch, 0) + 1
▶7 top = max(top, count[ch])
▶8 while right - left + 1 - top > k:
▶9 count[s[left]] -= 1
▶10 left += 1
▶11 best = max(best, right - left + 1)
▶12 return best
stringA0A1B2A3B4B5A6count in windowA0B0changes needed0−0=0≤10lengthtopchangeskbestempty window, k allows 1 change
left0
top0highest count so far
best0
The window starts empty. Each letter will enter on the right; the bars count the letters inside the window, and the tiles below compute how many letters would have to change to make the window one letter.
stringA0L RA1B2A3B4B5A6count in windowA1 most commonB0changes needed1−1=0≤11lengthtopchangeskbestadd A → 0 changes needed → best 1
left0
top1highest count so far
best1
A enters at index 0. The window is 1 long and its most common letter appears once (a new high), so keeping that letter means changing 0. That fits the budget and beats the best length, so best becomes 1.
stringA0LA1RB2A3B4B5A6count in windowA2 most commonB0changes needed2−2=0≤12lengthtopchangeskbestadd A → 0 changes needed → best 2
left0
top2highest count so far
best2
A enters at index 1. The window is 2 long and its most common letter appears 2 times (a new high), so keeping that letter means changing 0. That fits the budget and beats the best length, so best becomes 2.
stringA0LA1B2RA3B4B5A6count in windowA2 most commonB1changes needed3−2=1≤13lengthtopchangeskbestadd B → 1 change needed → best 3
left0
top2highest count so far
best3
B enters at index 2. The window is 3 long and its most common letter appears 2 times, so keeping that letter means changing 1. That fits the budget and beats the best length, so best becomes 3.
stringA0LA1B2A3RB4B5A6count in windowA3 most commonB1changes needed4−3=1≤14lengthtopchangeskbestadd A → 1 change needed → best 4
left0
top3highest count so far
best4
A enters at index 3. The window is 4 long and its most common letter appears 3 times (a new high), so keeping that letter means changing 1. That fits the budget and beats the best length, so best becomes 4.
stringA0LA1B2A3B4RB5A6count in windowA3 most commonB2changes needed5−3=2>14lengthtopchangeskbestadd B → 2 changes needed, over k → move left
left0
top3highest count so far
best4
B enters at index 4. The window is 5 long and its most common letter appears 3 times, so keeping that letter means changing 2. That is more than k = 1, so this window cannot be made one letter; the left end has to move.
stringA0A1LB2A3B4RB5A6count in windowA2B2changes needed4−3=1≤14lengthtop (stored)changeskbestdrop A at index 0 → length 4, best stays 4
left1
top3highest count so far
best4
Remove A from the left. The window is back to length 4, the same as the best window, so it cannot set a record. top stays 3 although no letter in the window has that many now. That is safe: the window only grows past 4 when some letter reaches more than 3, and then top is exact again.
stringA0A1LB2A3B4B5RA6count in windowA2B3 most commonchanges needed5−3=2>14lengthtopchangeskbestadd B → 2 changes needed, over k → move left
left1
top3highest count so far
best4
B enters at index 5. The window is 5 long and its most common letter appears 3 times, so keeping that letter means changing 2. That is more than k = 1, so this window cannot be made one letter; the left end has to move.
stringA0A1B2LA3B4B5RA6count in windowA1B3 most commonchanges needed4−3=1≤14lengthtopchangeskbestdrop A at index 1 → length 4, best stays 4
left2
top3highest count so far
best4
Remove A from the left. The window is back to length 4, the same as the best window, so it cannot set a record. top is still the true highest count.
stringA0A1B2LA3B4B5A6Rcount in windowA2B3 most commonchanges needed5−3=2>14lengthtopchangeskbestadd A → 2 changes needed, over k → move left
left2
top3highest count so far
best4
A enters at index 6. The window is 5 long and its most common letter appears 3 times, so keeping that letter means changing 2. That is more than k = 1, so this window cannot be made one letter; the left end has to move.
stringA0A1B2A3LB4B5A6Rcount in windowA2B2changes needed4−3=1≤14lengthtop (stored)changeskbestdrop B at index 2 → length 4, best stays 4
left3
top3highest count so far
best4
Remove B from the left. The window is back to length 4, the same as the best window, so it cannot set a record. top stays 3 although no letter in the window has that many now. That is safe: the window only grows past 4 when some letter reaches more than 3, and then top is exact again.
stringA0A1B2A3B4B5A6count in windowA2B2changes needed4−3=1≤14lengthtop (stored)changeskbestanswer: 4
answer4
Every letter has entered once. The longest window that fitted the budget was 4 long, (the green tiles), so that many letters in a row can be made the same with at most 1 change.
05

Common pitfalls

Measuring the window before moving the left end

✗ Wrong
best = max(best, right - left + 1)
while right - left + 1 - top > k:
    count[s[left]] -= 1
    left += 1
✓ Right
while right - left + 1 - top > k:
    count[s[left]] -= 1
    left += 1
best = max(best, right - left + 1)

On "AABABBA" with k = 1 the window "AABAB" needs 2 changes, but measuring it first records 5. The answer is 4.

Indexing uppercase letters from 'a'

✗ Wrong
count = [0] * 26
count[ord(ch) - ord('a')] += 1
✓ Right
count = [0] * 26
count[ord(ch) - ord('A')] += 1

The string is uppercase, so ord('A') - ord('a') is -32 and even "A" raises an IndexError. In C++ the same slip reads outside the array without any error.

06

Edge cases

k is at least the length of s

No window ever needs more than k changes, so the left end never moves and the answer is the whole length.

k = 0, e.g. "AABBB"

No changes are allowed, so the answer is the longest run of one letter: 3 here.

07

Complexity

Time
O(n)
Space
O(1)
Each letter enters the window once and leaves at most once. The count table holds at most 26 letters, whatever the length of s.
08

Longest Repeating Character Replacement FAQ

How is this different from Longest Substring with At Most K Distinct Characters?

There k caps how many different letters a window may hold and nothing is changed. Here any letters may appear, and k caps how many of them you change, so the test is length minus the top count.

Why not try each of the 26 letters as the target?

That also works: for each letter, run a window that allows at most k other letters, and keep the best. It costs 26 passes. Using the window's most common letter does all 26 in one pass, because that letter is always the cheapest one to keep.