How to Explain Longest Repeating Character Replacement in a Coding Interview (Step-by-Step)

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

LeetCode 424 Medium

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

Example 1
Input: s = “ABAB”, k = 2
Output: 4
Explanation: Replace both A’s or both B’s → “AAAA” or “BBBB”
Example 2
Input: s = “AABABBA”, k = 1
Output: 4
Explanation: Replace one character → “AABBBBA” or similar → window of 4

Constraints

  • 1 <= s.length <= 10⁵
  • s consists of only uppercase English letters
  • 0 <= 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)

❌ Brute Force

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⁵

✅ Sliding Window

Expand right, shrink left when window becomes invalid

Time: O(n)

Space: O(26) = O(1)

Single pass — optimal


The Key Insight

💡 Core 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

replacements_needed = (right − left + 1) − max_freq
Window is valid when replacements_needed ≤ k

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’s 5 − 3 = 2 replacements. If k ≥ 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 moving right forward 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 exceed k — I shrink it by moving left forward. 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 decrease max_freq when the window shrinks. This is intentional — we only care about finding a window larger than the best we’ve seen. If max_freq can’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:

Sliding window states — blue = dominant char, yellow = replaced, red = invalid window
Step 1
A
A
B
A
B
B
A
Window: “A” | max_freq=1 | replacements=0 ≤ 1 ✓ | size=1
Step 3
A
A
B
A
B
B
A
Window: “AAB” | max_freq=2 (A) | replacements=3−2=1 ≤ 1 ✓ | size=3
Step 4
A
A
B
A
B
B
A
Window: “AABA” | max_freq=3 (A) | replacements=4−3=1 ≤ 1 ✓ | size=4 ⭐ best so far
Step 5 invalid
A
A
B
A
B
B
A
Window: “AABAB” | max_freq=3 (A) | replacements=5−3=2 > 1 ✗ → shrink left
After shrink
A
A
B
A
B
B
A
Window: “ABAB” | max_freq=2 | replacements=4−2=2 > 1 ✗ → window slides, size stays 4

Full step trace for "AABABBA", k = 1:

Rcharwindowmax_freqsize − max_freqvalid?result
0AA101
1AAA202
2BAAB213
3AAABA314 ★
4BAABAB→ABAB32→1✗ shrink4
5BABABB→BABB32→1✗ shrink4
6AABBA22✗ shrink4

Final answer: 4


Step 4: Highlight Edge Cases

1 k = 0
“With k = 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 when window_size − max_freq = 0, meaning all characters are already the same.”
2 k ≥ string length
“If k ≥ n, we can replace every character — the entire string is valid. The window never needs to shrink and result ends up as n. Handled naturally.”
3 All same characters
“e.g. "AAAA" with any kmax_freq always equals the window size so replacements needed is always 0. Window expands to the full string. Correct.”
4 Why we don’t decrease max_freq
“When we shrink the window, we don’t decrease max_freq even if the character we removed was the most frequent. This is fine — we only want windows larger than our current best. If max_freq can’t grow, the window slides at constant size. It can’t give us a worse answer.”

Step 5: State Time and Space Complexity

DimensionComplexityReason
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

If you can solve Longest Repeating Character Replacement cleanly, try these next:

💡 Practicing your explanations out loud is just as important as writing correct code. The best candidates aren’t the ones who solve it fastest — they’re the ones who make the interviewer feel like they’re thinking alongside them.
Scroll to Top