Longest Uniform Substring Under Bounded Character Edits
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
In an interview, a brief prompt asking for the "longest repeating-character segment after edits" leaves critical contract details unspecified — such as whether the edit budget is an upper bound or an exact count, whether the selected characters must sit side by side (a substring) or merely keep their relative order (a subsequence), whether the repeated character can vary freely or is fixed ahead of time, and what alphabet or return type is expected.
After clarifying those ambiguities, implement longest_repeating_character_replacement(s, k) under the following concrete specification:
- You are given an input string
sand an integerkrepresenting the maximum number of single-index character overwrites permitted (k >= 0; raiseValueErrorwhenk < 0). - In one edit, you may overwrite any single index of
swith any character. You may perform between0andkedits inclusive. - Compute and return the length of the longest contiguous slice
s[i : j]that can be made completely uniform (every character ins[i : j]identical), where the uniform character may be chosen freely for that slice. - Character comparisons are case-sensitive (
'a'and'A'are distinct),smay contain arbitrary characters, and an empty string""yields0.
Examples
Example 1
Input: s = "XYXYX", k = 2
Output: 5
Explanation: Across the full 5-character string, 'X' occurs 3 times and 'Y' occurs 2 times. Overwriting both 'Y' positions with 'X' spends 2 <= k edits and turns the entire string into "XXXXX" of length 5.
Example 2
Input: s = "XXYXXYYX", k = 1
Output: 5
Explanation: Within the prefix s[0:5] = "XXYXX", 'X' appears 4 times and 'Y' appears once, so overwriting s[2] with 'X' uses 1 <= k edit to form "XXXXX" (length 5). Every 6-character slice contains at least 2 minority characters and cannot be unified with k = 1.
Example 3
Input: s = "MMNNNMM", k = 0
Output: 3
Explanation: With zero edits permitted (k = 0), only an already-uniform contiguous run qualifies. The longest run is "NNN", which has length 3.
Example 4
Input: s = "PQRSTU", k = 2
Output: 3
Explanation: All six characters are distinct, so any slice of length L holds at most 1 copy of any character and requires L - 1 edits. Setting L - 1 <= 2 caps the achievable length at 3 (for instance, converting "PQR" into "PPP").
Constraints
0 <= len(s) <= 10^50 <= k <= 10^5(raiseValueErrorifk < 0)smay contain uppercase letters, lowercase letters, digits, or symbols; character equality is case-sensitive.- Your algorithm should run in $O(n \cdot U)$ time and $O(U)$ auxiliary space, where $n = \text{len}(s)$ and $U$ is the number of distinct characters appearing in
s.
Step-by-step walkthrough
Clarify the contract before choosing an algorithm
Open-ended string prompts reward engineers who surface hidden specification choices before writing a single line of code. Each design axis changes the algorithm:
Axis Question to ask first Algorithmic consequence ------------------------ ---------------------------------------- ----------------------------------------- 1. Edit budget Up to k edits, or mandatory exact k? "Up to k" keeps already-uniform runs valid. 2. Geometry Contiguous slice, or any subsequence? Subsequence needs 1 pass: min(n, max_count + k). 3. Winning character Picked freely per slice, or fixed char? Fixed char tracks 1 counter; free tracks all counts. 4. Output & character set Return max length or slice? Case rules? Hash map of counts handles arbitrary case-sensitive text.Once clarified, confirm the exact contract implemented here (matching Examples 1–4, such as
'XYXYX', 2 -> 5and'PQRSTU', 2 -> 3):- Up to
ksingle-index overwrites (k >= 0; raiseValueErrorfork < 0). - Chosen positions must form a contiguous substring.
- Each candidate window may freely select whichever character minimizes edits.
- Return the maximum achievable length (
0whens == ""), comparing characters case-sensitively ('a' != 'A').
- Up to
Compute the minimum edit cost of one window
Consider a contiguous slice
s[left .. right]of widthL = right - left + 1. What is the fewest edits required to make allLpositions hold the same character?Converting the entire slice to some character
cleaves existing copies ofcuntouched and overwrites the remainingL - count(c)indices. Minimizing edits therefore means keeping whichever character already has the highest count insides[left .. right]:edits_needed(window) = len(window) - max_frequency_in_windowIn
"XXYXX"(L = 5),'X'appears4times and'Y'appears once, so unifying onto'X'costs5 - 4 = 1edit.A window fits within budget whenever
edits_needed <= k. Inspecting alln * (n + 1) / 2slices separately would test roughly5 * 10^9pairs whenn = 100,000, which times out immediately.Key insight: edit cost grows monotonically with window width
Look at how
edits_neededbehaves when one new character is appended to the right end of a window:len(window)rises by1.max_frequency_in_windowrises by either1(if the new character extends or ties the leader) or0(otherwise).- Consequently,
len(window) - max_frequency_in_windowchanges by+0or+1— it never drops when expanding and never rises when shrinking!
That monotonicity enables a two-pointer sliding window (
leftandright):- Step
rightforward by1and incrementcounts[s[right]]. - While
(right - left + 1) - max(counts.values()) > k, decrementcounts[s[left]]and advanceleft += 1. (Becauses[left .. right]already exceeds budgetk, any wider windows[left .. right']starting at the sameleftwould also exceedk.) - Once the
whileloop finishes,s[left .. right]is the longest valid slice ending atright, so updatebest_length.
s = " X X Y X X Y Y X ", k = 1 ^ ^ left right = 4 window "XXYXX": len 5, max_freq ('X') = 4 -> 5 - 4 = 1 <= k (valid!) Next step (right = 5, char 'Y'): "X X Y X X Y" len 6, counts {X:4, Y:2} -> 6 - 4 = 2 > k (shrink left!) "X Y X X Y" len 5, counts {X:3, Y:2} -> 5 - 3 = 2 > k (shrink left!) "Y X X Y" len 4, counts {X:2, Y:2} -> 4 - 2 = 2 > k (shrink left!) "X X Y" len 3, counts {X:2, Y:1} -> 3 - 2 = 1 <= k (valid again!)Code the expand-and-shrink sliding window
Store per-character frequencies inside
s[left .. right]in a dictionarycounts. A dictionary handles uppercase, lowercase, digits, or symbols automatically while checkingmax(counts.values())inO(U)time forUdistinct characters.Because
k >= 0,leftcan never overtakeright: ifleftreachesright, the 1-character window has width1andmax_freq = 1, giving1 - 1 = 0 <= kand terminating thewhileloop.def longest_repeating_character_replacement(s: str, k: int) -> int: if k < 0: raise ValueError("k must be non-negative") # counts: maps character -> frequency inside the current window s[left..right] counts: Dict[str, int] = {} left = 0 best_length = 0 # Expand the sliding window one character to the right on each iteration. for right in range(len(s)): right_char = s[right] counts[right_char] = counts.get(right_char, 0) + 1 # Keep the window's most frequent character unchanged and replace every other position. # Shrink from the left while replacements needed (window_length - max_freq) exceed k. while (right - left + 1) - max(counts.values()) > k: left_char = s[left] counts[left_char] -= 1 left += 1 # Invariant: s[left..right] now needs at most k replacements to become uniform. window_length = right - left + 1 if window_length > best_length: best_length = window_length return best_lengthLeaving zero-count keys inside
countsis harmless because the non-empty slices[left .. right]always containss[right]with frequency at least1, so0never winsmax(counts.values()).Trace Example 2 end to end
Walk through
s = "XXYXXYYX"withk = 1:right s[right] shrink steps valid window counts cost best_length ----- -------- ---------------------------------- ------------ ---------- ---- ----------- 0 'X' none "X" {X:1} 0 1 1 'X' none "XX" {X:2} 0 2 2 'Y' none "XXY" {X:2, Y:1} 1 3 3 'X' none "XXYX" {X:3, Y:1} 1 4 4 'X' none "XXYXX" {X:4, Y:1} 1 5 5 'Y' "XXYXXY" (6-4=2>1) -> "XYXXY" (5-3=2>1) -> "YXXY" (4-2=2>1) -> "XXY" (3-2=1<=1) "XXY" {X:2, Y:1} 1 5 6 'Y' "XXYY" (4-2=2>1) -> "XYY" (3-2=1) "XYY" {X:1, Y:2} 1 5 7 'X' "XYYX" (4-2=2>1) -> "YYX" (3-2=1) "YYX" {X:1, Y:2} 1 5Notice
right = 5: popping the leading'X'reducedwindow_lengthfrom6to5and reducedmax(counts.values())from4to3, keeping the edit cost at2 > 1until three characters were popped. The peak valid width5("XXYXX"atright = 4) is preserved inbest_length.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def longest_repeating_character_replacement(s: str, k: int) -> int: if k < 0: raise ValueError("k must be non-negative") # counts: maps character -> frequency inside the current window s[left..right] counts: Dict[str, int] = {} left = 0 best_length = 0 # Expand the sliding window one character to the right on each iteration. for right in range(len(s)): right_char = s[right] counts[right_char] = counts.get(right_char, 0) + 1 # Keep the window's most frequent character unchanged and replace every other position. # Shrink from the left while replacements needed (window_length - max_freq) exceed k. while (right - left + 1) - max(counts.values()) > k: left_char = s[left] counts[left_char] -= 1 left += 1 # Invariant: s[left..right] now needs at most k replacements to become uniform. window_length = right - left + 1 if window_length > best_length: best_length = window_length return best_length✅ Submit now — all tests should pass.
Intuition & how it works
Imagine inspecting a row of painted tiles when you have enough paint to recolor at most k tiles into one matching shade. In an interview, you first clarify the contract: are we choosing a substring (an unbroken block of adjacent characters) rather than a subsequence (characters picked in order with gaps allowed), is k an upper limit rather than an exact count, and may each candidate block freely pick its winning color? Under that standard contract, the cheapest way to unify any block is to leave its most frequent character untouched and overwrite every other position — spending window_length - max_frequency edits. We then sweep an elastic frame (s[left .. right], called a sliding window) across s: advance right one slot per turn, and whenever the frame needs more than k edits, pull left forward until it fits within budget again.
A brute-force check evaluates all n * (n + 1) / 2 substrings from scratch, recounting overlapping spans in O(n^2) to O(n^3) time — billions of operations when n = 100,000. Because appending a character to a window never decreases the number of edits needed (a monotonic property, meaning the cost only moves in one direction as the window widens), any left endpoint left that exceeds budget k at right will also exceed k for every right' > right, so advancing left never discards an optimal answer.
Trace the prefix "XXYXXY" from Example 2 with k = 1:
- right = 0..4 ("X" -> "XX" -> "XXY" -> "XXYX" -> "XXYXX"): width 5, 'X' appears 4 times, edits needed = 5 - 4 = 1 <= 1, updating best_length = 5.
- right = 5 ("XXYXXY"): width 6, 'X' appears 4 times, cost 6 - 4 = 2 > 1. Advancing left steps through "XYXXY" (5 - 3 = 2 > 1) and "YXXY" (4 - 2 = 2 > 1) before stopping at "XXY" (3 - 2 = 1 <= 1), while best_length stays 5.
Complexity
Let n = len(s) and U be the number of distinct characters appearing in s (for instance, at most 26 for uppercase ASCII letters).
- Time:
O(n * U)(O(n)for a bounded alphabet). Indexrightadvancesntimes andleftadvances at mostntimes across the entire execution (amortizedO(1)pointer steps per outer iteration, meaning the total inner-loop work averaged across allnsteps is constant). Each check callsmax(counts.values())over at mostUentries at most2ntimes. - Space:
O(U). Thecountsdictionary holds one integer counter per distinct character encountered ins.
Edge cases
- Empty input (
s = ""): The loop executes zero iterations and returns0. - Single character (
s = "Z", k = 0): Window"Z"requires1 - 1 = 0 <= 0edits and returns1. - Zero budget (
k = 0): No edits are allowed (window_length == max_freq), reducing to the longest contiguous run of identical characters ("MMNNNMM", 0 -> 3). - Generous budget (
k >= len(s) - 1): Even when all characters differ ("ABC", k = 5), the window never shrinks and returnslen(s) = 3. - Window winner differs from global majority: In
"AXAXAXAXABBYBB"withk = 1,'A'leads globally (5copies), yet the best window"BBYBB"(length5) unifies onto'B'. Re-evaluatingmax(counts.values())per window handles this automatically. - Case sensitivity and symbols:
'a'and'A'occupy separate keys incounts("aAaA", 1 -> 3). - Negative
k: RaisesValueErrorimmediately since no non-empty window can require fewer than0edits.
Common mistakes
- Coding before clarifying ambiguities: Skipping questions about contiguity, fixed vs free target characters, or
<= kvs== kmisses what an intentionally open prompt tests. - Fixing the target character to the global mode: Locking onto whichever character appears most in the entire string fails whenever another character forms a denser local cluster (
"AXAXAXAXABBYBB", k = 1). - Shrinking with
whileand returninglen(s) - left: Whenwhileshrinks the window on a noisy suffix,len(s) - leftreflects only the final valid suffix rather than the historical peak ("AAAB", k = 0would return1instead of3). Always recordbest_length. - Returning
min(len(s), max_global_count + k): That formula solves the subsequence variant and ignores adjacency ("XYXY", k = 0would return2instead of1). - Recording
best_lengthbefore thewhileloop: Measuringright - left + 1prior to shrinking counts invalid windows that violate budgetk.
Alternative approaches
- Per-character two-pointer scan: Iterate over every unique character
targetinset(s)and run a simple sliding window allowing at mostkmismatches!= target(shown in the first follow-up). That also takesO(n * U)time usingO(1)working state per pass. - Non-shrinking
O(n)window with monotonicmax_count: Trackmax_countas the largest single-character count observed in any window so far without decrementing it whenleftmoves, and replacewhilewithifso the frame width only grows or slides sideways. Returninglen(s) - leftruns inO(n)independent ofU, though justifying why a stalemax_countnever produces a false positive is subtler to explain live than our invariant-maintainingwhileloop.
Follow-up questions
- Suppose the caller also specifies a mandatory character
targetthat the final uniform substring must consist of. How does the window validity check and space usage simplify? Every index wheres[i] != targetmust be overwritten, so the validity condition simplifies tomismatch_count <= k. You can drop thecountsdictionary andmax(...)scan altogether in favor of a single integermismatches, cutting time to strictO(n)and auxiliary space toO(1)for any alphabet size:
python
def longest_for_target(s: str, k: int, target: str) -> int:
left = 0
mismatches = 0 # positions in s[left..right] not equal to target
best_length = 0
for right in range(len(s)):
if s[right] != target:
mismatches += 1
while mismatches > k:
if s[left] != target:
mismatches -= 1
left += 1
best_length = max(best_length, right - left + 1)
return best_length
- If the requirement relaxed from a contiguous substring to a non-contiguous subsequence, why is a sliding window no longer needed and what is the closed-form answer? A sliding window exists solely to keep every chosen index contiguous between
leftandright. Once non-adjacent indices are allowed, gaps carry zero penalty: pick whichever charactercoccurs most frequently across the whole string (max_total_counttimes), include all of its occurrences, and overwrite up tokother positions anywhere instoc(capped bylen(s)). No window is needed — the closed-form answer is0whens == ""andmin(len(s), max_total_count + k)otherwise, computable in oneO(n)frequency pass.
Follow-up questions
- Suppose the caller also specifies a mandatory character `target` that the final uniform substring must consist of. How does the window validity check and space usage simplify?
- If the requirement relaxed from a contiguous substring to a non-contiguous subsequence, why is a sliding window no longer needed and what is the closed-form answer?
Similar questions
- Clarifying Conflict Constraints in House-Selection Optimization
- Multi-Tenant Ad Serving and Attribution Platform
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging