Shrink again at R = 5Adding B makes counts A:2, B:3 over length 5, so remove items[1] = A and move L right to 2.
A0A1LB2A3B4RB5A6
range[2..5] = "BABB"directionL: 1 -> 2 because 5 - 3 > 1formula4 - historical max 3 = 1best4
saved stateA count1B count3
key A count
2→1
key B count
2→3
L
1→2
Finish without exceeding fourABBA also needs two edits: current maximum 2, historical maximum 3. Earlier AABA already established the valid best length 4.
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?
Sources and provenance
Full interview answer 21 min read
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
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
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
Read the first AA count becomes 1 and largest_count becomes 1; 1 - 1 = 0 replacements, so best becomes 1.
LRA0A1B2A3B4B5A6
range[0..0] = "A"formula1 - 1 = 0 <= 1best1
saved stateA count1B count0
key A count
not shown→1
key B count
not shown→0
range
empty before reading index 0→[0..0] = "A"
Extend to AAAt R = 1, A count and largest_count become 2; 2 - 2 = 0, so best becomes 2.
LA0RA1B2A3B4B5A6
range[0..1] = "AA"formula2 - 2 = 0 <= 1best2
saved stateA count2B count0
key A count
1→2
R
0→1
range
[0..0] = "A"→[0..1] = "AA"
Spend one replacementAt R = 2, counts are A:2 and B:1; 3 - largest_count 2 = 1, so "AAB" fits and best becomes 3.
LA0A1RB2A3B4B5A6
range[0..2] = "AAB"formula3 - 2 = 1 <= 1best3
saved stateA count2B count1
key B count
0→1
R
1→2
range
[0..1] = "AA"→[0..2] = "AAB"
Reach the best lengthAt R = 3, A count and largest_count become 3; 4 - 3 = 1, so "AABA" fits and best becomes 4.
LA0A1B2RA3B4B5A6
range[0..3] = "AABA"formula4 - 3 = 1 <= 1best4
saved stateA count3B count1
key A count
2→3
R
2→3
range
[0..2] = "AAB"→[0..3] = "AABA"
Shrink after the budget breaksABAB has current maximum 2 but historical maximum 3. Its length 4 is retained, not certified valid.
Shrink again at R = 5Adding B makes counts A:2, B:3 over length 5, so remove items[1] = A and move L right to 2.
A0A1LB2A3B4RB5A6
range[2..5] = "BABB"directionL: 1 -> 2 because 5 - 3 > 1formula4 - historical max 3 = 1best4
saved stateA count1B count3
key A count
2→1
key B count
2→3
L
1→2
Finish without exceeding fourABBA also needs two edits: current maximum 2, historical maximum 3. Earlier AABA already established the valid best length 4.
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 substring
Length
Current max F
Historical max H
Actual edits
Valid for 1?
AABA
4
3
3
1
Yes
ABAB
4
2
3
2
No
BABB
4
3
3
1
Yes
ABBA
4
2
3
2
No
Actual cost is W−F: every character outside the largest current group needs an edit.
The fast test uses W−H≤k, where largest_count never decreases and H≥F.
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 H leaves length H+k; further fixed-H steps cannot grow it.
Before any shrink at H, the window retains H real copies. If H 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 defaultdictdef 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 O(n) and space is O(d) for distinct characters seen, not the replacement budget.
Each endpoint advances at most n 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 O(nd) 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
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 H+k.
Appending adds one position; repair removes at most one because H 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-H ceiling. To establish a larger length, H 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 O(n) time and constant auxiliary state.
Neither adaptation silently accepts negative budgets or a multi-code-point target; their stated input contracts still apply.