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 s and an integer k representing the maximum number of single-index character overwrites permitted (k >= 0; raise ValueError when k < 0).
  • In one edit, you may overwrite any single index of s with any character. You may perform between 0 and k edits inclusive.
  • Compute and return the length of the longest contiguous slice s[i : j] that can be made completely uniform (every character in s[i : j] identical), where the uniform character may be chosen freely for that slice.
  • Character comparisons are case-sensitive ('a' and 'A' are distinct), s may contain arbitrary characters, and an empty string "" yields 0.

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^5
  • 0 <= k <= 10^5 (raise ValueError if k < 0)
  • s may 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

  1. 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 -> 5 and 'PQRSTU', 2 -> 3):

    • Up to k single-index overwrites (k >= 0; raise ValueError for k < 0).
    • Chosen positions must form a contiguous substring.
    • Each candidate window may freely select whichever character minimizes edits.
    • Return the maximum achievable length (0 when s == ""), comparing characters case-sensitively ('a' != 'A').
  2. Compute the minimum edit cost of one window

    Consider a contiguous slice s[left .. right] of width L = right - left + 1. What is the fewest edits required to make all L positions hold the same character?

    Converting the entire slice to some character c leaves existing copies of c untouched and overwrites the remaining L - count(c) indices. Minimizing edits therefore means keeping whichever character already has the highest count inside s[left .. right]:

    edits_needed(window) = len(window) - max_frequency_in_window
    

    In "XXYXX" (L = 5), 'X' appears 4 times and 'Y' appears once, so unifying onto 'X' costs 5 - 4 = 1 edit.

    A window fits within budget whenever edits_needed <= k. Inspecting all n * (n + 1) / 2 slices separately would test roughly 5 * 10^9 pairs when n = 100,000, which times out immediately.

  3. Key insight: edit cost grows monotonically with window width

    Look at how edits_needed behaves when one new character is appended to the right end of a window:

    • len(window) rises by 1.
    • max_frequency_in_window rises by either 1 (if the new character extends or ties the leader) or 0 (otherwise).
    • Consequently, len(window) - max_frequency_in_window changes by +0 or +1 — it never drops when expanding and never rises when shrinking!

    That monotonicity enables a two-pointer sliding window (left and right):

    1. Step right forward by 1 and increment counts[s[right]].
    2. While (right - left + 1) - max(counts.values()) > k, decrement counts[s[left]] and advance left += 1. (Because s[left .. right] already exceeds budget k, any wider window s[left .. right'] starting at the same left would also exceed k.)
    3. Once the while loop finishes, s[left .. right] is the longest valid slice ending at right, so update best_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!)
    
  4. Code the expand-and-shrink sliding window

    Store per-character frequencies inside s[left .. right] in a dictionary counts. A dictionary handles uppercase, lowercase, digits, or symbols automatically while checking max(counts.values()) in O(U) time for U distinct characters.

    Because k >= 0, left can never overtake right: if left reaches right, the 1-character window has width 1 and max_freq = 1, giving 1 - 1 = 0 <= k and terminating the while loop.

    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
    

    Leaving zero-count keys inside counts is harmless because the non-empty slice s[left .. right] always contains s[right] with frequency at least 1, so 0 never wins max(counts.values()).

  5. Trace Example 2 end to end

    Walk through s = "XXYXXYYX" with k = 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         5
    

    Notice right = 5: popping the leading 'X' reduced window_length from 6 to 5 and reduced max(counts.values()) from 4 to 3, keeping the edit cost at 2 > 1 until three characters were popped. The peak valid width 5 ("XXYXX" at right = 4) is preserved in best_length.

  6. 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). Index right advances n times and left advances at most n times across the entire execution (amortized O(1) pointer steps per outer iteration, meaning the total inner-loop work averaged across all n steps is constant). Each check calls max(counts.values()) over at most U entries at most 2n times.
  • Space: O(U). The counts dictionary holds one integer counter per distinct character encountered in s.

Edge cases

  • Empty input (s = ""): The loop executes zero iterations and returns 0.
  • Single character (s = "Z", k = 0): Window "Z" requires 1 - 1 = 0 <= 0 edits and returns 1.
  • 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 returns len(s) = 3.
  • Window winner differs from global majority: In "AXAXAXAXABBYBB" with k = 1, 'A' leads globally (5 copies), yet the best window "BBYBB" (length 5) unifies onto 'B'. Re-evaluating max(counts.values()) per window handles this automatically.
  • Case sensitivity and symbols: 'a' and 'A' occupy separate keys in counts ("aAaA", 1 -> 3).
  • Negative k: Raises ValueError immediately since no non-empty window can require fewer than 0 edits.

Common mistakes

  • Coding before clarifying ambiguities: Skipping questions about contiguity, fixed vs free target characters, or <= k vs == k misses 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 while and returning len(s) - left: When while shrinks the window on a noisy suffix, len(s) - left reflects only the final valid suffix rather than the historical peak ("AAAB", k = 0 would return 1 instead of 3). Always record best_length.
  • Returning min(len(s), max_global_count + k): That formula solves the subsequence variant and ignores adjacency ("XYXY", k = 0 would return 2 instead of 1).
  • Recording best_length before the while loop: Measuring right - left + 1 prior to shrinking counts invalid windows that violate budget k.

Alternative approaches

  • Per-character two-pointer scan: Iterate over every unique character target in set(s) and run a simple sliding window allowing at most k mismatches != target (shown in the first follow-up). That also takes O(n * U) time using O(1) working state per pass.
  • Non-shrinking O(n) window with monotonic max_count: Track max_count as the largest single-character count observed in any window so far without decrementing it when left moves, and replace while with if so the frame width only grows or slides sideways. Returning len(s) - left runs in O(n) independent of U, though justifying why a stale max_count never produces a false positive is subtler to explain live than our invariant-maintaining while loop.

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? Every index where s[i] != target must be overwritten, so the validity condition simplifies to mismatch_count <= k. You can drop the counts dictionary and max(...) scan altogether in favor of a single integer mismatches, cutting time to strict O(n) and auxiliary space to O(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 left and right. Once non-adjacent indices are allowed, gaps carry zero penalty: pick whichever character c occurs most frequently across the whole string (max_total_count times), include all of its occurrences, and overwrite up to k other positions anywhere in s to c (capped by len(s)). No window is needed — the closed-form answer is 0 when s == "" and min(len(s), max_total_count + k) otherwise, computable in one O(n) frequency pass.

Follow-up questions

Similar questions

More Digitalocean interview questions

All 3 Digitalocean questions →