#424

Longest Repeating Character Replacement

Medium Variable window + max frequency

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

You may change at most k characters of an uppercase string. Return the longest substring that can be made of one repeated letter.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: change at most k letters to get the longest run of one letter.

Why this works: a window is fine when (length - count of its most common letter) ≤ k, because those other letters are the ones you change.

Example: "AABABBA", k = 1

"AABA": length 4, most common A=3 → 1 change ✓"AABAB": 5 - 3 = 2 > 1 → slide leftbest 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Recomputing the true max frequency every time you shrink — correct but unnecessary; the stale maximum still gives the right answer.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(26).
Topic: Sliding Window
🎬 Episode 10: video coming soon