Longest Repeating Character Replacement

medium

You are given a string s of uppercase English letters and an integer k. You may choose at most k positions and replace each with any uppercase letter.

Return the length of the longest substring containing a single repeated letter you can obtain after performing at most k replacements.

Hints

Inside a window, which characters would you replace to unify it?
Keep the most frequent letter and replace the rest — cost is length minus max frequency.
Grow while (length - maxFreq) <= k; slide the left edge when it exceeds k.

Common doubts

Unifying the window is cheapest by converting every non-majority character to the most frequent one. There are exactly (length - maxFreq) of those.
No. A stale (too-large) maxFreq only ever keeps the window the same size or lets it grow, and the answer is monotonic, so it never overstates the achievable length.
No — you never need to know which letter is the majority, only its count, because you'd always convert toward whichever is most frequent.

Interview follow-ups

Track the (left, right) of the best window and the argmax of the counts within it when you record a new best.
Nothing structural — the count map just has more keys; space stays O(alphabet size).

Fun facts

  • The 'stale maxFreq is safe' argument is a favorite interview follow-up — it trips people up because the window's true max can drop while the recorded one doesn't.
  • length - maxFreq is the Hamming distance to the nearest all-same string over that window.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: s = "ABAB", k = 2
Output: 4
Replace the two A's (or two B's) to make "AAAA" or "BBBB" — length 4.
Example 2
Input: s = "AABABBA", k = 1
Output: 4
Replace one character in "AABA" (or "ABBB") to get a run of 4 identical letters.
Constraints

- 1 <= s.length <= 10^5 - s consists of only uppercase English letters. - 0 <= k <= s.length

Solve this problem →