Browse curriculum

FAANGPrep Sprint

Longest Repeating Character Replacement

Replace characters to get the longest repeating character substring.

Examples

Input:s = "ABAB", k = 2
Output:4
Explain:

Both changes can go to the same letter: flip the two 'A's to get "BBBB", or the two 'B's to get "AAAA".

Input:s = "AABABBA", k = 1
Output:4
Explain:

With one change, turn the middle 'A' into 'B': "AABBBBA" now holds the run "BBBB", 4 letters long.

Problem Understanding

The input is an uppercase string s and a budget k. One operation overwrites a single character with any other uppercase letter, and you may spend up to k operations.

Goal: return the length of the longest substring that can be made entirely of one repeated letter within that budget.

Algorithm Strategy

We use a Sliding Window to check if a valid window exists. A window (substring) is valid if we can turn it into all same characters using at most k replacements.

Logic:

  1. Validity Check: Replacements Needed = Window Length - Count of Most Frequent Char.
    • If Replacements Needed <= k, the window is valid. We try to expand it (increment right).
    • If Replacements Needed > k, the window involves too many changes. We perform one shrink step (increment left) to try and make it valid again.
  2. We maintain a frequency map (or array of size 26) to track counts of characters in the current window.
  3. We keep track of max_count, the highest count any character has reached in a window so far. It is never decreased, which is why the map is never re-scanned; the section below explains why a stale value still gives the right answer.

Interactive Visualization

k = 1

EMPTY WINDOW

A

0

A

1

B

2

A

3

B

4

B

5

A

6

Length

—

maxCount

0

Needed

—

Best

0

count

Empty

 

left at 0, no counts, maxCount 0. At most 1 replacement

Next

Add 'A' at 0: count['A'] = 1

String

k

Watch how the window expands and only shrinks when the number of replacements needed exceeds k.