Starting Positions of Longest Uniform Substrings

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a non-empty uppercase ASCII string s ('A' through 'Z') and a non-negative edit budget k, you can overwrite up to k character positions inside a candidate substring with arbitrary uppercase letters.

Call a contiguous substring convertible if k or fewer single-character edits within that slice suffice to make every character in the slice identical. Each candidate slice is judged independently with the full budget k.

Let L denote the greatest length achieved by any convertible substring of s. Compute how many distinct 0-based start indices i (0 <= i <= len(s) - L) yield a convertible substring s[i : i + L] of that peak length L.

def count_max_length_substrings(s: str, k: int) -> int:

Examples

Example 1

Input: s = "DDRCDDR", k = 1
Output: 3

No slice of length 4 contains three matching letters, so the peak convertible length is L = 3. Three starting indices produce a length-3 slice needing at most 1 edit: index 0 ("DDR" -> "DDD"), index 3 ("CDD" -> "DDD"), and index 4 ("DDR" -> "DDD").

Example 2

Input: s = "WXYZZV", k = 1
Output: 2

With one allowed edit, the longest convertible slices have length L = 3: "YZZ" at index 2 and "ZZV" at index 3 can both become "ZZZ". Every other length-3 slice contains three distinct letters and requires 2 edits.

Example 3

Input: s = "KKQQKK", k = 0
Output: 3

Because k = 0 forbids edits, a slice is convertible only when all of its letters already match. The longest existing identical runs have length L = 2, starting at indices 0 ("KK"), 2 ("QQ"), and 4 ("KK").

Example 4

Input: s = "MNPQ", k = 3
Output: 1

Overwriting three letters turns the entire 4-character string into a single repeated letter, giving L = 4 with index 0 as its sole starting position.

Constraints

  • 1 <= len(s) <= 10^5
  • Every character of s is an uppercase English letter ('A'–'Z').
  • 0 <= k <= len(s)

Step-by-step walkthrough

  1. Understand the goal and split into two passes

    We receive an uppercase string s ('A'–'Z') and an edit budget k:

    • A contiguous slice is convertible if overwriting k or fewer positions inside it can make every character in that slice match. (Each candidate slice gets the full budget k independently.)
    • Let L be the peak length achieved by any convertible substring of s.
    • Return how many distinct starting indices i yield a convertible length-L slice s[i : i + L].

    Once we know the peak length L, each starting index i maps to at most one candidate slice s[i : i + L]. That lets us divide the task into two clean steps: first find L, and then count how many fixed-width windows of length L are convertible.

  2. Why brute force is too slow

    A direct approach checks every possible substring s[i:j] to find the longest valid length L, then checks every substring of length L to count valid starts.

    For a string of length n, there are n * (n + 1) / 2 substrings. When n = 100,000, that is roughly 5,000,000,000 substrings—thousands of times too slow for a one-second limit, though great as a brute-force reference on tiny random strings.

  3. Key formula: replacements needed in any window

    Suppose we are looking at a single substring (window) of length w. To turn all w characters into the same letter using as few replacements as possible, which target letter should we pick?

    We should keep every copy of whichever letter already appears most frequently in the window, and replace all the other characters:

    replacements_needed = window_length - max_letter_count_in_window
    window is valid   <=> replacements_needed <= k
    
    Examples with k = 1:
      "DDR"  -> length 3, 'D' appears 2 times -> 3 - 2 = 1 <= 1 (convertible!)
      "DDRC" -> length 4, 'D' appears 2 times -> 4 - 2 = 2 > 1 (over budget)
    

    Notice what happens as a window changes size:

    • Removing a character shrinks window_length by 1 and decreases max_letter_count by at most 1, so replacements_needed can never increase (a valid window stays valid when shrunk).
    • Adding a character grows window_length by 1 and increases max_letter_count by at most 1, so replacements_needed can never decrease (an invalid window stays invalid if we only expand it).

    That monotonic behavior means we can find the longest valid window ending at each right index by moving a left pointer strictly forward!

  4. Pass 1: find the maximum valid length with two pointers

    We maintain a 26-slot frequency table counts for the current window s[left : right + 1]. As right steps from 0 to len(s) - 1:

    1. Add s[right] into counts.
    2. While (right - left + 1) - max(counts) > k, the window needs too many changes, so remove s[left] from counts and increment left.
    3. Now s[left : right + 1] is the longest valid window ending at right; update max_length.

    Because any 1-character window has 1 - 1 = 0 <= k replacements needed, the while loop always stops before left passes right.

    def letter_index(ch: str) -> int:
        """Map an uppercase English letter 'A'..'Z' to its array index 0..25."""
        return ord(ch) - ord("A")
    
    
    def longest_valid_length(s: str, k: int) -> int:
        """Pass 1: Find the global maximum length L of a substring convertible with <= k changes."""
        # counts: 26-slot frequency table for the current window s[left : right + 1]
        counts = [0] * 26
        left = 0
        max_length = 0
    
        for right in range(len(s)):
            enter_idx = letter_index(s[right])
            counts[enter_idx] += 1
    
            # Keep every copy of the window's most frequent letter and replace the rest;
            # shrink from the left whenever replacements needed exceed budget k.
            while (right - left + 1) - max(counts) > k:
                leave_idx = letter_index(s[left])
                counts[leave_idx] -= 1
                left += 1
    
            window_length = right - left + 1
            if window_length > max_length:
                max_length = window_length
    
        return max_length
    
  5. Pass 2: count every valid window of length max_length

    Once target_length = max_length is known, we slide a fixed-size window of length target_length across s from left to right:

    • Add s[right] to counts.
    • Whenever right >= target_length, s[right - target_length] has just fallen off the left edge of the window, so subtract 1 from its count.
    • Starting at right = target_length - 1 (the first index where the window holds target_length characters), check whether target_length - max(counts) <= k.

    Two subtle bugs are avoided automatically here:

    1. No double counting on ties: A window like "AB" with k = 1 can become either "AA" or "BB", yet we ask target_length - max(counts) <= k once for that window, so index 0 is counted once, not twice.
    2. No stale maximum: Some solutions for finding max_length alone keep a running max_freq variable that never decreases when characters leave the window. In Pass 2 that trick would be wrong—if "AA" gave max_freq = 2 on "AABB" (k = 0), a stale max_freq = 2 would falsely accept "AB"! Recomputing max(counts) over the 26 slots takes constant O(26) time and always uses the window's true majority count.
    def count_valid_windows(s: str, k: int, target_length: int) -> int:
        """Pass 2: Count how many starting indices have a valid substring of exact length target_length."""
        # counts: exact character counts inside the sliding window of size up to target_length
        counts = [0] * 26
        valid_starts = 0
    
        for right in range(len(s)):
            enter_idx = letter_index(s[right])
            counts[enter_idx] += 1
    
            # Evict the character that slid out of the fixed-size window on the left.
            if right >= target_length:
                leave_idx = letter_index(s[right - target_length])
                counts[leave_idx] -= 1
    
            # Once the window holds target_length characters, test its true current max(counts).
            # Testing the window once counts each starting index at most once (even if 2 letters tie).
            if right >= target_length - 1:
                replacements_needed = target_length - max(counts)
                if replacements_needed <= k:
                    valid_starts += 1
    
        return valid_starts
    
  6. Trace Example 1 across both passes

    Let's trace s = "DDRCDDR" with k = 1:

    Pass 1 (finding max_length):
    right  window after shrinking    max(counts)  needed  max_length
      0    "D"    [0..0]                  1         0         1
      1    "DD"   [0..1]                  2         0         2
      2    "DDR"  [0..2]                  2         1         3
      3    "RC"   [2..3] (shrunk twice)   1         1         3
      4    "CD"   [3..4] (shrunk once)    1         1         3
      5    "CDD"  [3..5]                  2         1         3
      6    "DDR"  [4..6] (shrunk once)    2         1         3
    Result of Pass 1: max_length = 3
    
    Pass 2 (testing every window of length 3):
    start  right  window  counts          max(counts)  3 - max  <= 1?
      0      2    "DDR"   D:2, R:1             2          1      Yes (valid_starts = 1)
      1      3    "DRC"   D:1, R:1, C:1        1          2      No
      2      4    "RCD"   R:1, C:1, D:1        1          2      No
      3      5    "CDD"   C:1, D:2             2          1      Yes (valid_starts = 2)
      4      6    "DDR"   D:2, R:1             2          1      Yes (valid_starts = 3)
    Final answer: 3
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def letter_index(ch: str) -> int:
        """Map an uppercase English letter 'A'..'Z' to its array index 0..25."""
        return ord(ch) - ord("A")
    
    
    def longest_valid_length(s: str, k: int) -> int:
        """Pass 1: Find the global maximum length L of a substring convertible with <= k changes."""
        # counts: 26-slot frequency table for the current window s[left : right + 1]
        counts = [0] * 26
        left = 0
        max_length = 0
    
        for right in range(len(s)):
            enter_idx = letter_index(s[right])
            counts[enter_idx] += 1
    
            # Keep every copy of the window's most frequent letter and replace the rest;
            # shrink from the left whenever replacements needed exceed budget k.
            while (right - left + 1) - max(counts) > k:
                leave_idx = letter_index(s[left])
                counts[leave_idx] -= 1
                left += 1
    
            window_length = right - left + 1
            if window_length > max_length:
                max_length = window_length
    
        return max_length
    
    
    def count_valid_windows(s: str, k: int, target_length: int) -> int:
        """Pass 2: Count how many starting indices have a valid substring of exact length target_length."""
        # counts: exact character counts inside the sliding window of size up to target_length
        counts = [0] * 26
        valid_starts = 0
    
        for right in range(len(s)):
            enter_idx = letter_index(s[right])
            counts[enter_idx] += 1
    
            # Evict the character that slid out of the fixed-size window on the left.
            if right >= target_length:
                leave_idx = letter_index(s[right - target_length])
                counts[leave_idx] -= 1
    
            # Once the window holds target_length characters, test its true current max(counts).
            # Testing the window once counts each starting index at most once (even if 2 letters tie).
            if right >= target_length - 1:
                replacements_needed = target_length - max(counts)
                if replacements_needed <= k:
                    valid_starts += 1
    
        return valid_starts
    
    
    def count_max_length_substrings(s: str, k: int) -> int:
        max_length = longest_valid_length(s, k)
        return count_valid_windows(s, k, max_length)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine repainting a contiguous row of fence pickets—a substring (a continuous slice of characters from s)—so every picket in that slice ends up the same color, while repainting at most k pickets. For any candidate slice, the cheapest color to match is whichever color already appears most often inside that slice: you leave all copies of that majority color untouched and repaint the remaining window_length - max_count pickets.

Checking all O(n^2) substrings one by one takes billions of steps when n = 100,000, and trying to count max-length starting positions on the fly in a single pass gets tripped up whenever a longer valid substring appears later and invalidates earlier counts. Instead, we split the work into two fast linear passes using a sliding window (a contiguous subarray s[left : right + 1] maintained incrementally as its endpoints move right). In Pass 1, two pointers (left and right) expand right one character at a time and advance left whenever window_length - max(counts) > k, finding the global maximum valid length L. In Pass 2, a fixed-size window of exact length L slides across s once and counts how many starting positions need at most k replacements.

Let's trace s = "WXYZZV" with k = 1:

  1. Pass 1 (find L): the window grows to "WX" (length 2, 1 edit), shrinks "WXY" (3 - 1 = 2 > 1) to "XY", shrinks "XYZ" to "YZ", expands to "YZZ" (length 3, 'Z' appears twice so 3 - 2 = 1 <= 1, setting L = 3), and shifts to "ZZV" (also length 3), finishing with L = 3.
  2. Pass 2 (count length-3 windows):
    • start 0 ("WXY"): max_count = 1, needs 3 - 1 = 2 > 1 -> no;
    • start 1 ("XYZ"): max_count = 1, needs 3 - 1 = 2 > 1 -> no;
    • start 2 ("YZZ"): max_count = 2, needs 3 - 2 = 1 <= 1 -> count = 1;
    • start 3 ("ZZV"): max_count = 2, needs 3 - 2 = 1 <= 1 -> count = 2.
  3. The function returns 2.

Complexity

Let n be len(s). The alphabet size is fixed at 26 uppercase English letters ('A'–'Z').

  • Time: O(26 * n), which simplifies to O(n). In Pass 1, right advances n times and left advances at most n times across the entire loop (at most 2n pointer moves total); in Pass 2, right advances n times. Each step updates O(1) array slots and calls max(counts) across a fixed 26-element list.
  • Space: O(1) auxiliary space. Both passes allocate only a 26-integer list counts and a handful of scalar variables, independent of n.

Edge cases

  • k = 0 (no replacements allowed): window_length - max(counts) <= 0 holds only when max(counts) == window_length, so Pass 1 finds the longest existing run of identical characters and Pass 2 counts how many runs tie for that length (e.g., "AABBBCCCDD" -> 2 for "BBB" and "CCC").
  • k == len(s) (can replace the entire string): Pass 1 never shrinks left, returning L = n, and Pass 2 tests the single full-string window at index 0, returning 1.
  • All distinct characters (possible when n <= 26, e.g., "ABCDEF" with k = 1): every window has max(counts) = 1, so L = min(n, k + 1) and all n - L + 1 windows of length L are valid (5 starts for "ABCDEF", k = 1).
  • Single-character string ("Z", k = 0 or k = 1): L = 1 and index 0 is valid, returning 1.
  • Window valid via two different target letters ("AB", k = 1): can become "AA" or "BB", and is rightly counted once because we count distinct starting indices i, not (i, letter) pairs.
  • Different majority letters achieving L at different indices ("AABAACCCC", k = 1): start 0 ("AABAA" -> all 'A') and start 4 ("ACCCC" -> all 'C') both achieve L = 5 and both count (2).

Common mistakes

  • Reusing the "non-decreasing max_freq" trick in Pass 2. Keeping a historical max_freq that never drops when characters leave the window is valid when finding L in Pass 1, but breaks Pass 2: on "AABB" with k = 0, max_freq stays 2 after leaving "AA", falsely counting "AB" as valid and returning 3 instead of 2.
  • Summing counts separately per letter (for target in 'A'..'Z') without deduplicating starts. On "AB" with k = 1, start 0 works for 'A' and also works for 'B', double-counting index 0 unless you deduplicate indices.
  • Treating the budget k as shared across all candidate substrings simultaneously. Every starting index i is evaluated independently with its own budget of up to k edits ("BAAAB" with k = 1 achieves L = 4 at both i = 0 and i = 1, returning 2).
  • Off-by-one when starting to count in Pass 2. The first full window of length L ends at right = L - 1 (covering s[0 : L]), whereas eviction of s[right - L] starts one step later at right = L.

Alternative approaches

  • 2D prefix sum array. Build a prefix sum array (a table prefix[c][i] storing how many times letter c appears in the first i characters s[:i], so any slice's count is prefix[c][r] - prefix[c][l] in O(1) time). Combined with binary search on L or Pass 1's sliding window, it runs in O(26 * n) time, but uses O(26 * n) extra memory instead of O(1).
  • Per-letter sliding window. Run 26 separate two-pointer scans—one per target letter 'A'–'Z'—allowing at most k non-target letters inside the window, and mark valid length-L starts in a boolean array valid_start[i] to avoid double counting. Takes O(26 * n) time and O(n) extra space.

Follow-up questions

  • How would the algorithm change if overwriting position i had an individual non-negative cost c[i] under a total budget B? Turning a window into all copies of letter ch leaves every ch untouched and pays for every other index inside the window, costing window_total_cost - letter_cost_sum[ch]. Replace the 26 character counts with 26 cost totals letter_cost_sum[0..25] plus window_total_cost: because c[i] >= 0, shrinking a window never increases window_total_cost - max(letter_cost_sum), so the same Pass 1 two-pointer shrink loop and Pass 2 fixed-window scan run in O(26 * n) time and O(1) extra space (if costs instead depend on both source and destination letters cost[src][dst] >= 0, maintain a 26-element array cost_to_make[target] for the current window and check min(cost_to_make) <= B).

  • Is it possible to achieve strict O(n) runtime and constant extra memory, and what changes if the alphabet size is unbounded? Because uppercase ASCII has a fixed 26-letter alphabet, max(counts) inspects 26 slots per step, so our two-pass solution already achieves O(n) time and O(1) auxiliary space. If the alphabet size sigma can grow arbitrarily large, scanning all counts on every step would take O(n * sigma) time; you can remove the per-step sigma factor by pairing a hash map of counts with a frequency-of-frequencies bucket table buckets[f] (how many distinct symbols currently have frequency f in the window) and current_max: incrementing a count from f to f + 1 updates current_max = max(current_max, f + 1), while decrementing a count from current_max to current_max - 1 drops current_max by 1 whenever buckets[current_max] reaches 0, running in O(n) time and O(min(n, sigma)) space.

  • How would you adapt the implementation if the caller asked for the valid substrings themselves rather than the count of start indices? In Pass 2, whenever target_length - max(counts) <= k at index right, compute start = right - target_length + 1 and collect s[start : right + 1] (if pre-edit slices are wanted) or best_letter * target_length (if post-edit uniform strings are wanted). Clarify expected output size with the interviewer first: materializing up to n slices of length L can require O(n * L) time and memory in the worst case (for instance "AB" * 50000 with k = 1000 produces 98,000 slices of length 2,001), so returning (start, start + L) index intervals or deduplicating with a set is often cleaner.

Follow-up questions

Similar questions

More Pinduoduo interview questions

All 17 Pinduoduo questions →