How to Explain Longest Repeating Character Replacement in a Coding Interview (Step-by-Step)
Longest Repeating Character Replacement is the quintessential variable-size sliding window problem. The trick isn’t the window mechanics — it’s the validity formula. Once you can explain why window_size − max_freq ≤ k determines validity, the rest is straightforward.
In this post, you’ll learn exactly how to walk an interviewer through this problem: the core formula, how the window expands and contracts, a full step-by-step trace, and the subtle gotcha about not decreasing max_freq.
Problem Statement
You are given a string s and an integer k. You can choose any character in the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Examples
Output: 4
Explanation: Replace both A’s or both B’s → “AAAA” or “BBBB”
Output: 4
Explanation: Replace one character → “AABBBBA” or similar → window of 4
Constraints
1 <= s.length <= 10⁵sconsists of only uppercase English letters0 <= k <= s.length
What Is the Problem?
“I need to find the longest contiguous substring where, after replacing at most k characters, all characters in the window are the same. The replacement strategy is always to change minority characters into the most frequent one.”
Step 1: Start With the Brute Force (Then Dismiss It)
Try every substring, count replacements needed for each
Time: O(n² · 26) — every pair × frequency count
Space: O(26) = O(1)
Too slow for n = 10⁵
Expand right, shrink left when window becomes invalid
Time: O(n)
Space: O(26) = O(1)
Single pass — optimal
The Key Insight
Within any window, the minimum replacements needed = window size minus the count of the most frequent character. Those are the characters we’d replace to make the whole window uniform.
So a window is valid as long as: window_size − max_freq ≤ k. If it exceeds k, we need to shrink the window from the left.
The Validity Formula — The Heart of This Problem
Spend time on this formula in the interview. Draw it out if needed:
“In a window of size 5 with the most frequent character appearing 3 times, I need to replace the other 2 characters. That’s5 − 3 = 2replacements. Ifk ≥ 2, this window is valid.”
Step 2: Explain the Algorithm in Plain English
“I use a sliding window with left and right pointers. I expand the window by movingrightforward one character at a time, updating a frequency map and tracking the max frequency in the window. If the window becomes invalid — meaning replacements needed exceedk— I shrink it by movingleftforward. At every step I track the maximum valid window size seen.”
Step 3: Talk Through the Code
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
count = {} # Frequency map of chars in current window
max_freq = 0 # Max frequency of any single char in window
left = 0
result = 0
for right in range(len(s)):
count[s[right]] = count.get(s[right], 0) + 1 # Expand window
max_freq = max(max_freq, count[s[right]]) # Update max freq
# Check if window is valid: replacements needed <= k
window_size = right - left + 1
if window_size - max_freq > k:
count[s[left]] -= 1 # Shrink window from left
left += 1
result = max(result, right - left + 1) # Update best valid window
return result
There’s a subtle but important optimisation here worth calling out explicitly:
“Notice we never decreasemax_freqwhen the window shrinks. This is intentional — we only care about finding a window larger than the best we’ve seen. Ifmax_freqcan’t grow, the window just slides forward at the same size rather than shrinking. This keeps the time complexity O(n).”
Visual Walkthrough
Tracing s = "AABABBA", k = 1:
Full step trace for "AABABBA", k = 1:
| R | char | window | max_freq | size − max_freq | valid? | result |
|---|---|---|---|---|---|---|
| 0 | A | A | 1 | 0 | ✓ | 1 |
| 1 | A | AA | 2 | 0 | ✓ | 2 |
| 2 | B | AAB | 2 | 1 | ✓ | 3 |
| 3 | A | AABA | 3 | 1 | ✓ | 4 ★ |
| 4 | B | AABAB→ABAB | 3 | 2→1 | ✗ shrink | 4 |
| 5 | B | ABABB→BABB | 3 | 2→1 | ✗ shrink | 4 |
| 6 | A | ABBA | 2 | 2 | ✗ shrink | 4 |
Final answer: 4
Step 4: Highlight Edge Cases
“Withk = 0, no replacements are allowed. The longest valid window is the longest run of a single repeating character. The formula still works: window is valid only whenwindow_size − max_freq = 0, meaning all characters are already the same.”
“Ifk ≥ n, we can replace every character — the entire string is valid. The window never needs to shrink andresultends up asn. Handled naturally.”
“e.g."AAAA"with anyk—max_freqalways equals the window size so replacements needed is always 0. Window expands to the full string. Correct.”
“When we shrink the window, we don’t decreasemax_freqeven if the character we removed was the most frequent. This is fine — we only want windows larger than our current best. Ifmax_freqcan’t grow, the window slides at constant size. It can’t give us a worse answer.”
Step 5: State Time and Space Complexity
| Dimension | Complexity | Reason |
|---|---|---|
| Time | O(n) | Each character is added and removed from the window at most once |
| Space | O(1) | Frequency map has at most 26 keys — fixed alphabet size |
Interview Checklist for Longest Repeating Character Replacement
- Restate — “longest window where replacements needed ≤ k”
- Mention brute force O(n²) and dismiss it
- State the key insight — replacements = window_size − max_freq
- Explain the validity formula clearly — derive it, don’t just state it
- Explain sliding window mechanics — expand right, shrink left when invalid
- Call out the max_freq gotcha — we never decrease it, and explain why
- Handle k=0 and k≥n edge cases
- State O(n) time and O(1) space — fixed 26-char alphabet
- Ask before coding, don’t just dive in
Related Problems to Practice
If you can solve Longest Repeating Character Replacement cleanly, try these next:
