Longest Repeating Character Replacement

35 min · characterReplacement()

A few well-placed edits can turn a noisy stretch of letters into one clean run.

You're given an uppercase string s and a budget k. You may replace at most k characters, changing each chosen character to any uppercase English letter. Return the length of the longest substring — a contiguous stretch — that can become one repeated letter after those replacements.

A few ground rules:

  • Every character in the chosen substring must be the same after the edits.
  • You may use fewer than k replacements, including none.
  • The replacement letter doesn't have to be the letter that appears first.

Constraints

  • 1 <= s.length <= 100_000
  • 0 <= k <= s.length
  • s contains only uppercase English letters A through Z.

Hints

Price one window

In a chosen window, keep its most common letter and replace everything else. If the window length is w and that letter appears max_count times, the price is w - max_count replacements.

Grow until the budget breaks

Move a right edge across the string while counting letters. When the window's price exceeds k, move the left edge inward until growth is safe again.

Keep the best majority count

The largest letter count you've seen in the active scan never needs to decrease. A stale larger count may delay shrinking, but it can't invent a better answer than the valid window that established that count.

Follow-up

How would your solution change if the input alphabet weren't fixed to 26 letters?

Visible cases

Examples

Example 1

ready
Input
s = "ABAB"
k = 2
Expected
4
Why
replace both copies of either letter to make a run of 4

Example 2

ready
Input
s = "AABABBA"
k = 1
Expected
4
Why
one replacement can make a four-letter run, but not five

Example 3

ready
Input
s = "ABCDE"
k = 1
Expected
2
Why
any adjacent pair can be made equal with one replacement

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite