Longest Repeating Character Replacement (LeetCode 424): Solution and Explanation

Medium
Hash Table
String
Sliding Window

You are given a string of uppercase letters and an integer k. You may change at most k characters to any other uppercase letter. Return the length of the longest substring that can be made of a single repeated letter after those changes.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

For a fixed substring, the cheapest way to make it uniform is to keep its most common letter and replace everything else. So a window of length len is achievable exactly when len - maxFreq <= k, where maxFreq is the count of its most frequent letter. Checking every substring with that test is O(n²) windows, or O(26 × n²) with counting, which is far too slow for long strings.

The condition behaves nicely for a sliding window. If a window is valid, shrinking it keeps it valid, and if it is invalid, growing it cannot help. So you can extend a right pointer one character at a time and, whenever the window breaks the rule, move the left pointer forward until it is valid again. Every window you record is legal, and you track the longest one.

There is a well known subtlety in how the reference code keeps maxf. It only ever increases, even when the left pointer drops letters that were part of the maximum. That looks like a bug but is not. The answer can only improve when some letter reaches a new, higher frequency, because the window length is bounded by maxf + k. A stale maxf might let the window stay a bit larger than strictly valid, but it never causes the recorded best to exceed a length that was truly achieved earlier, so the result is still correct and you avoid rescanning 26 counts.

Approach: Sliding window with a running max frequency

  1. Keep a count dictionary for letters in the window, a left pointer l, the best length res, and maxf for the highest frequency seen.
  2. For each right index r, increment count[s[r]] and update maxf with that new count.
  3. While the window length r - l + 1 minus maxf exceeds k, decrement the count of s[l] and move l right.
  4. Update res with the current window length r - l + 1.
  5. After the loop finishes, return res.

Step-by-step example

s = "AABABBA", k = 1
  1. For r = 0 to 2 the window grows to "AAB". A has count 2, so 3 - 2 = 1 replacement is allowed, and res becomes 3.
  2. At r = 3 the window is "AABA" with A at 3, which needs one replacement. res becomes 4.
  3. At r = 4 the window "AABAB" needs 5 - 3 = 2 replacements, which is too many. Dropping the first A makes it "ABAB", which is valid with length 4.
  4. At r = 5, B reaches 3 but maxf stays 3. The window "ABABB" needs 2 replacements, so the left A is dropped, leaving "BABB" with length 4.
  5. At r = 6 the window "BABBA" needs 2 replacements, so the left B is dropped and the window becomes "ABBA" with length 4.
  6. The loop ends and returns 4, for example by turning "AABA" into "AAAA".

Code: Python, Java, C++

1class Solution:
2    def characterReplacement(self, s: str, k: int) -> int:
3        count = {}
4        res = 0
5        l = 0
6        maxf = 0
7        
8        for r in range(len(s)):
9            count[s[r]] = 1 + count.get(s[r], 0)
10            maxf = max(maxf, count[s[r]])
11            
12            while (r - l + 1) - maxf > k:
13                count[s[l]] -= 1
14                l += 1
15            res = max(res, r - l + 1)
16        return res

Time and space complexity

Time

O(n)

Each index is added once when r passes it and removed at most once when l passes it, so both pointers move at most n steps in total.

Space

O(1)

The count map holds at most 26 uppercase letters no matter how long the string is.

Other approaches

Recompute max frequency from the counts (time O(26 × n), space O(1))

Instead of the monotonic maxf, compute max(count.values()) each time you check the window. It is easier to reason about and still linear for a fixed alphabet, at the cost of a factor of 26.

Window per target letter (time O(26 × n), space O(1))

For each of the 26 letters, run a sliding window that counts how many characters differ from that letter and keeps the count at or below k. Take the best length across all letters.

Common mistakes

  • Comparing against k with the wrong expression. The number of replacements needed is the window length minus maxf, not the number of distinct letters.
  • Trying to decrease maxf when the left pointer moves without recomputing it correctly, which can produce a value lower than the true maximum.
  • Updating res before shrinking the window, which can record an invalid window length.
  • Assuming lowercase letters or digits. The constraint says uppercase English letters, which is what keeps the counts bounded.

Frequently asked questions

Why doesn't maxf need to decrease when the window shrinks?

A longer valid window can only appear once some letter's count exceeds the old maxf. Keeping the stale higher value never lets res exceed a length that was actually valid earlier, so the final answer stays correct.

What is the time complexity of Longest Repeating Character Replacement?

It is O(n), since both pointers only move forward through the string. The space is O(1) because the alphabet is limited to 26 letters.

How do you know when the window is invalid?

A window needs length - maxFreq changes to become one letter. When that number is greater than k, the window is invalid and the left edge must move.