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
sis an uppercase English letter ('A'–'Z'). 0 <= k <= len(s)
Step-by-step walkthrough
Understand the goal and split into two passes
We receive an uppercase string
s('A'–'Z') and an edit budgetk:- A contiguous slice is convertible if overwriting
kor fewer positions inside it can make every character in that slice match. (Each candidate slice gets the full budgetkindependently.) - Let
Lbe the peak length achieved by any convertible substring ofs. - Return how many distinct starting indices
iyield a convertible length-Lslices[i : i + L].
Once we know the peak length
L, each starting indeximaps to at most one candidate slices[i : i + L]. That lets us divide the task into two clean steps: first findL, and then count how many fixed-width windows of lengthLare convertible.- A contiguous slice is convertible if overwriting
Why brute force is too slow
A direct approach checks every possible substring
s[i:j]to find the longest valid lengthL, then checks every substring of lengthLto count valid starts.For a string of length
n, there aren * (n + 1) / 2substrings. Whenn = 100,000, that is roughly5,000,000,000substrings—thousands of times too slow for a one-second limit, though great as a brute-force reference on tiny random strings.Key formula: replacements needed in any window
Suppose we are looking at a single substring (window) of length
w. To turn allwcharacters 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_lengthby1and decreasesmax_letter_countby at most1, soreplacements_neededcan never increase (a valid window stays valid when shrunk). - Adding a character grows
window_lengthby1and increasesmax_letter_countby at most1, soreplacements_neededcan 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
rightindex by moving aleftpointer strictly forward!- Removing a character shrinks
Pass 1: find the maximum valid length with two pointers
We maintain a 26-slot frequency table
countsfor the current windows[left : right + 1]. Asrightsteps from0tolen(s) - 1:- Add
s[right]intocounts. - While
(right - left + 1) - max(counts) > k, the window needs too many changes, so removes[left]fromcountsand incrementleft. - Now
s[left : right + 1]is the longest valid window ending atright; updatemax_length.
Because any 1-character window has
1 - 1 = 0 <= kreplacements needed, thewhileloop always stops beforeleftpassesright.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- Add
Pass 2: count every valid window of length max_length
Once
target_length = max_lengthis known, we slide a fixed-size window of lengthtarget_lengthacrosssfrom left to right:- Add
s[right]tocounts. - Whenever
right >= target_length,s[right - target_length]has just fallen off the left edge of the window, so subtract1from its count. - Starting at
right = target_length - 1(the first index where the window holdstarget_lengthcharacters), check whethertarget_length - max(counts) <= k.
Two subtle bugs are avoided automatically here:
- No double counting on ties: A window like
"AB"withk = 1can become either"AA"or"BB", yet we asktarget_length - max(counts) <= konce for that window, so index0is counted once, not twice. - No stale maximum: Some solutions for finding
max_lengthalone keep a runningmax_freqvariable that never decreases when characters leave the window. In Pass 2 that trick would be wrong—if"AA"gavemax_freq = 2on"AABB"(k = 0), a stalemax_freq = 2would falsely accept"AB"! Recomputingmax(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- Add
Trace Example 1 across both passes
Let's trace
s = "DDRCDDR"withk = 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: 3Complete 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:
- 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 so3 - 2 = 1 <= 1, settingL = 3), and shifts to"ZZV"(also length 3), finishing withL = 3. - Pass 2 (count length-3 windows):
- start
0("WXY"):max_count = 1, needs3 - 1 = 2 > 1-> no; - start
1("XYZ"):max_count = 1, needs3 - 1 = 2 > 1-> no; - start
2("YZZ"):max_count = 2, needs3 - 2 = 1 <= 1-> count =1; - start
3("ZZV"):max_count = 2, needs3 - 2 = 1 <= 1-> count =2.
- start
- 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,
rightadvances n times andleftadvances at most n times across the entire loop (at most 2n pointer moves total); in Pass 2,rightadvances n times. Each step updates O(1) array slots and callsmax(counts)across a fixed 26-element list. - Space: O(1) auxiliary space. Both passes allocate only a 26-integer list
countsand a handful of scalar variables, independent of n.
Edge cases
k = 0(no replacements allowed):window_length - max(counts) <= 0holds only whenmax(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"->2for"BBB"and"CCC").k == len(s)(can replace the entire string): Pass 1 never shrinksleft, returningL = n, and Pass 2 tests the single full-string window at index0, returning1.- All distinct characters (possible when
n <= 26, e.g.,"ABCDEF"withk = 1): every window hasmax(counts) = 1, soL = min(n, k + 1)and alln - L + 1windows of lengthLare valid (5starts for"ABCDEF",k = 1). - Single-character string (
"Z",k = 0ork = 1):L = 1and index0is valid, returning1. - 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 indicesi, not(i, letter)pairs. - Different majority letters achieving
Lat different indices ("AABAACCCC",k = 1): start0("AABAA"-> all'A') and start4("ACCCC"-> all'C') both achieveL = 5and both count (2).
Common mistakes
- Reusing the "non-decreasing
max_freq" trick in Pass 2. Keeping a historicalmax_freqthat never drops when characters leave the window is valid when findingLin Pass 1, but breaks Pass 2: on"AABB"withk = 0,max_freqstays2after leaving"AA", falsely counting"AB"as valid and returning3instead of2. - Summing counts separately per letter (
for target in 'A'..'Z') without deduplicating starts. On"AB"withk = 1, start0works for'A'and also works for'B', double-counting index0unless you deduplicate indices. - Treating the budget
kas shared across all candidate substrings simultaneously. Every starting indexiis evaluated independently with its own budget of up tokedits ("BAAAB"withk = 1achievesL = 4at bothi = 0andi = 1, returning2). - Off-by-one when starting to count in Pass 2. The first full window of length
Lends atright = L - 1(coverings[0 : L]), whereas eviction ofs[right - L]starts one step later atright = L.
Alternative approaches
- 2D prefix sum array. Build a prefix sum array (a table
prefix[c][i]storing how many times lettercappears in the firsticharacterss[:i], so any slice's count isprefix[c][r] - prefix[c][l]in O(1) time). Combined with binary search onLor 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 mostknon-target letters inside the window, and mark valid length-Lstarts in a boolean arrayvalid_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
chleaves everychuntouched and pays for every other index inside the window, costingwindow_total_cost - letter_cost_sum[ch]. Replace the 26 character counts with 26 cost totalsletter_cost_sum[0..25]pluswindow_total_cost: becausec[i] >= 0, shrinking a window never increaseswindow_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 letterscost[src][dst] >= 0, maintain a 26-element arraycost_to_make[target]for the current window and checkmin(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 sizesigmacan grow arbitrarily large, scanning all counts on every step would take O(n * sigma) time; you can remove the per-stepsigmafactor by pairing a hash map of counts with a frequency-of-frequencies bucket tablebuckets[f](how many distinct symbols currently have frequencyfin the window) andcurrent_max: incrementing a count fromftof + 1updatescurrent_max = max(current_max, f + 1), while decrementing a count fromcurrent_maxtocurrent_max - 1dropscurrent_maxby1wheneverbuckets[current_max]reaches0, 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) <= kat indexright, computestart = right - target_length + 1and collects[start : right + 1](if pre-edit slices are wanted) orbest_letter * target_length(if post-edit uniform strings are wanted). Clarify expected output size with the interviewer first: materializing up to n slices of lengthLcan require O(n * L) time and memory in the worst case (for instance"AB" * 50000withk = 1000produces98,000slices of length2,001), so returning(start, start + L)index intervals or deduplicating with asetis often cleaner.
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?
- Is it possible to achieve strict O(n) runtime and constant extra memory, and what changes if the alphabet size is unbounded?
- How would you adapt the implementation if the caller asked for the valid substrings themselves rather than the count of start indices?
Similar questions
- Obstacle-Aware Clockwise Spiral Walk
- Longest Strictly Increasing Subsequence
- Fixed-Capacity LRU Cache
- Fewest Perfect Squares Summing to Target
- Construct Clockwise Spiral Square Matrix
- Spiral Numbering of a Square Grid
More Pinduoduo interview questions
- Obstacle-Aware Clockwise Spiral Walk Medium
- Engineering Background, Transition Drivers, and Offer Criteria Easy
- Articulating Company Fit and Career Decision Pillars Hard Pro
- Service Scope, Data Contracts, and Cross-Team Dependencies Hard Pro
- Longest Uniform Substring Within Replacement Budget Medium Pro
- Demonstrating a Core Strength and an Active Growth Area Hard Pro
- Clockwise Spiral Grid Traversal Medium Pro
- Longest Strictly Increasing Subsequence Medium Pro
- Walking Through Your Most Challenging Engineering Project Medium Pro
- Fixed-Capacity LRU Cache Medium Pro