Skip to content
mlmentorship

Longest Repeating Character Replacement

Replace at most `k` letters so the longest possible substring has one repeated letter.

Published · 21 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Longest Repeating Character Replacement

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A Python string text and a nonnegative integer replacements. Output. Return the greatest substring length that can contain one repeated character after at most replacements edits. Rules. Each edit replaces one character with any other character. The chosen substring must be contiguous; its final repeated character can be chosen freely. Use exact code points. Return a length without modifying the string; empty input returns zero. Example. For text = "AABABBA" and one replacement, return 4. The substring "AABA" becomes "AAAA" by replacing its single B.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Keep a candidate length while window length - historical max frequency stays within k = 1.

Problem trace

The saved best length need not describe the final displayed window

Input and goalReplace at most `k` letters so the longest possible substring has one repeated letter.
Initialize the scanFor AABABBA, use budget 1. Start both boundaries at 0, historical maximum at 0, and best at 0.
LRA0A1B2A3B4B5A6
rangeempty before reading index 0budgetk = 1best0
saved stateempty
L
0
R
0
range
empty before reading index 0

Recognize it
Use it for a longest contiguous span that may change at most k items into one repeated value; window length minus its dominant frequency is the required edit count.
Keep true
After each shrink, window length is at most largest_count + k, where largest_count is the greatest frequency seen while expanding. best is the greatest retained candidate length seen so far.
Reuse it
When edits can homogenize a window, rewrite validity as window size minus the best keepable group. A monotone summary can be enough for maximizing length even when it overestimates a later window frequency.
For AABABBA, use budget 1. Start both boundaries at 0, historical maximum at 0, and best at 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: How can the algorithm return four when its final displayed window needs two edits and the budget is one?
Full interview answer 21 min read
Reading depth

Find the longest contiguous string segment that can become uniform within a fixed replacement budget.

Problem

Input. A Python string text and a nonnegative integer replacements.

Output. Return the greatest substring length that can contain one repeated character after at most replacements edits.

Rules. Each edit replaces one character with any other character. The chosen substring must be contiguous; its final repeated character can be chosen freely. Use exact code points. Return a length without modifying the string; empty input returns zero.

Example. For text = "AABABBA" and one replacement, return 4. The substring "AABA" becomes "AAAA" by replacing its single B.

Picture: A Retained Candidate Is Not Always Valid

Problem trace

The saved best length need not describe the final displayed window

Worked example: the saved best need not describe the final shown windowAABA needs one replacement and has length 4. A later ABBA window needs two; it does not invalidate the earlier saved optimum of 4.A later invalid window does not erasethe earlier valid witnessSaved witness: AABAAABA1 edits needed; budget 1: validLater window: ABBAABBA2 edits needed; budget 1: invalidSaved length four still has the validAABA witness.
Read it this way: AABA needs one replacement and has length 4. A later ABBA window needs two; it does not invalidate the earlier saved optimum of 4. Does the later invalid ABBA window invalidate the saved AABA witness?
Reference drawing

Problem trace

The saved best length need not describe the final displayed window

Worked example: the saved best need not describe the final shown windowAABA needs one replacement and has length 4. A later ABBA window needs two; it does not invalidate the earlier saved optimum of 4.A later invalid window does not erasethe earlier valid witnessSaved witness: AABAAABA1 edits needed; budget 1: validLater window: ABBAABBA2 edits needed; budget 1: invalidSaved length four still has the validAABA witness.
Execution trace
Input and goalReplace at most `k` letters so the longest possible substring has one repeated letter.
Initialize the scanFor AABABBA, use budget 1. Start both boundaries at 0, historical maximum at 0, and best at 0.
LRA0A1B2A3B4B5A6
rangeempty before reading index 0budgetk = 1best0
saved stateempty
L
0
R
0
range
empty before reading index 0

Recognize it
Use it for a longest contiguous span that may change at most k items into one repeated value; window length minus its dominant frequency is the required edit count.
Keep true
After each shrink, window length is at most largest_count + k, where largest_count is the greatest frequency seen while expanding. best is the greatest retained candidate length seen so far.
Reuse it
When edits can homogenize a window, rewrite validity as window size minus the best keepable group. A monotone summary can be enough for maximizing length even when it overestimates a later window frequency.
For AABABBA, use budget 1. Start both boundaries at 0, historical maximum at 0, and best at 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: How can the algorithm return four when its final displayed window needs two edits and the budget is one?
Read it this way: AABA needs one replacement and has length 4. A later ABBA window needs two; it does not invalidate the earlier saved optimum of 4. Does the later invalid ABBA window invalidate the saved AABA witness?

The figure’s k is code parameter replacements; L, R are left, right.

Retained substringLengthCurrent max Historical max Actual editsValid for 1?
AABA4331Yes
ABAB4232No
BABB4331Yes
ABBA4232No

Actual cost is : every character outside the largest current group needs an edit. The fast test uses , where largest_count never decreases and . This optimistic bound can retain invalid windows.

A shrink occurs only when even the optimistic test fails, so the removed start cannot form a valid current substring. Extending a fixed-start substring cannot lower its edit cost.

A shrink with fixed leaves length ; further fixed- steps cannot grow it. Before any shrink at , the window retains real copies. If rises, a live count establishes it. Therefore each new best length has a real witness, even if later slides do not.

Code

from collections import defaultdict

def character_replacement(text: str, replacements: int) -> int:
   counts: dict[str, int] = defaultdict(int)
   left = 0
   largest_count = 0
   best = 0

   for right, char in enumerate(text):
      counts[char] += 1
      largest_count = max(largest_count, counts[char])

      while right - left + 1 - largest_count > replacements:
         counts[text[left]] -= 1
         left += 1

      best = max(best, right - left + 1)

   return best

Expected time is and space is for distinct characters seen, not the replacement budget. Each endpoint advances at most times; ordinary hash costs are assumed.

Change 1: Return a Valid Substring

New task. Return text whose actual edit cost fits the budget.

Picture and change. Recompute the current maximum during repair. Save boundaries only after true validity; retain the first best on ties.

Code.

def replacement_witness(text, replacements):
   counts = {}
   left = best_left = best_length = 0
   for right, character in enumerate(text):
      counts[character] = counts.get(character, 0) + 1
      while right - left + 1 - max(counts.values()) > replacements:
         counts[text[left]] -= 1
         left += 1
      if right - left + 1 > best_length:
         best_left, best_length = left, right - left + 1
   return text[best_left:best_left + best_length]

Check. ("AABABBA", 1) returns "AABA"; empty text returns "".

Use when. Current or winning-window validity must be inspectable. Recomputation costs in a general alphabet; a fixed alphabet bounds that factor. Copying adds output-length cost.

Change 2: Fix the Destination Character

New task. Every retained character must become one specified code point, target.

Picture and change. Track exact non-target count. Removing a non-target character refunds one edit.

Code.

def longest_to_target(text, replacements, target):
   left = cost = best = 0
   for right, character in enumerate(text):
      cost += character != target
      while cost > replacements:
         cost -= text[left] != target
         left += 1
      best = max(best, right - left + 1)
   return best

Check. ("AABABBA", 1, "A") gives 4; ("BBBB", 1, "A") gives 1, not 4.

Use when. The destination is fixed rather than chosen separately for each window.

Failure: Returning the Final Candidate

Final "ABBA" needs two edits. It is not a valid one-edit certificate, even though the reported optimum 4 is correct.

Transfer Check

Can the historical maximum validate every window for counting or enumeration?

Reasoned Answer

No. Its optimization proof is length-specific. Use the true current statistic or supply a separate counting proof.

Why the Relaxation Is Specific to This Objective

Before each append, retained length is at most . Appending adds one position; repair removes at most one because cannot decrease. Thus retained length never decreases. Sliding at a fixed best length can produce invalid candidates without inventing a new best.

Before the first shrink at a historical value, the window still contains the copies that established it. After that shrink, length has reached its fixed- ceiling. To establish a larger length, must rise from a current count. This supplies the genuine witness behind every new maximum; it does not certify every later candidate of that size.

The exact witness variant deliberately buys a stronger, easier-to-inspect invariant by recomputing current counts’ maximum. The target-specific variant instead tracks an exact scalar cost, giving expected time and constant auxiliary state. Neither adaptation silently accepts negative budgets or a multi-code-point target; their stated input contracts still apply.