Peak Substring Frequency Under Character Bounds
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
You are given a string s of lowercase English letters along with three integers: max_letters, min_size, and max_size.
A contiguous substring w of s is valid when it satisfies both bounds simultaneously:
min_size <= len(w) <= max_sizewcontains no more thanmax_lettersunique characters.
Compute the highest frequency achieved by any valid substring across s. If s has no valid substrings at all, return 0.
def max_substring_occurrences(s: str, max_letters: int, min_size: int, max_size: int) -> int:
Frequency is defined by how many distinct starting indices i satisfy s[i : i + len(w)] == w. Overlapping matches at different starting offsets each contribute 1 to w's frequency. Because only the peak integer frequency is requested, ties among multiple valid substrings require no tie-breaking rule.
Examples
Example 1
- Input:
s = "xyxzwxyxxyx",max_letters = 2,min_size = 3,max_size = 5 - Output:
3 - Explanation: Substring
"xyx"has length3(within[3, 5]) and uses2unique letters ('x'and'y'). It begins at offsets0,5, and8, giving frequency3. Windows containing'z'or'w'alongside'x'and'y'use3unique letters and are invalid, while no valid substring of length3,4, or5appears more than3times.
Example 2
- Input:
s = "zzzzzz",max_letters = 1,min_size = 4,max_size = 5 - Output:
3 - Explanation: Substring
"zzzz"uses1unique letter and begins at overlapping offsets0,1, and2(3total occurrences), beating"zzzzz"which begins only at offsets0and1.
Example 3
- Input:
s = "pqrstu",max_letters = 2,min_size = 4,max_size = 6 - Output:
0 - Explanation: Every character in
"pqrstu"is distinct, so any substring of length4or longer contains at least4unique letters, exceedingmax_letters = 2.
Constraints
1 <= len(s) <= 10^5- Every character of
sis a lowercase English letter ('a'–'z'). 1 <= max_letters <= 261 <= min_size <= max_size <= min(26, len(s))
Step-by-step walkthrough
Understand what makes a substring valid
We want the peak frequency among all valid substrings of
s, where a substringwqualifies when:- its length satisfies
min_size <= len(w) <= max_size, and - it uses at most
max_lettersunique characters.
Matches are counted by starting offset, so overlapping windows at different offsets each count toward the total:
s = "zzzzzz", max_letters = 1, min_size = 4, max_size = 5 index: 0 1 2 3 4 5 string: z z z z z z [z z z z] <-- start = 0 ("zzzz") [z z z z] <-- start = 1 ("zzzz", overlaps start = 0, still counts!) [z z z z] <-- start = 2 ("zzzz", overlaps start = 1, still counts!) Total occurrences of "zzzz" = 3 (note: "zzzzzz".count("zzzz") in Python gives 1, not 3!)If no substring satisfies both bounds, we return
0.- its length satisfies
Why checking every allowed length does unnecessary work
A direct brute-force solution loops over every allowed length
Lfrommin_sizetomax_size, slices every substring of lengthL, checkslen(set(w)) <= max_letters, and tallies counts in a dictionary.Because
max_size <= 26, that brute force inspects up to26 * 100,000 = 2.6 * 10^6substrings and stores up to millions of strings in memory. That works as a small-input test oracle, yet almost all of those lengths turn out to be redundant.Key insight: why length `min_size` always wins (or ties)
Suppose some longer valid substring
wof lengthL > min_sizeoccursktimes ins. Look atp, the prefix made of the firstmin_sizecharacters ofw:s = "x y x z w x y x x y x", min_size = 3, max_size = 5, max_letters = 2 Suppose a length-4 substring "xyxx" occurred k times: Every occurrence of [x y x x] begins with [x y x] at the exact same start offset! Plus [x y x] can ALSO appear at other offsets (0 and 8) where "xyxx" does not match!Compare
pagainstwon every condition:- Frequency (
count(p) >= count(w)): Whereverwbegins at offseti,palso begins at offseti(andpmight appear at extra offsets too). - Unique letters (
unique(p) <= unique(w) <= max_letters): Every character ofpis already insidew, so dropping the tail can only keep or shrink the set of unique letters—never enlarge it. - Length (
len(p) == min_size):min_sizealways lies within[min_size, max_size].
Therefore, every longer valid substring is matched or beaten by its own
min_sizeprefix! We only ever need to examine substrings of lengthmin_size;max_sizenever changes the answer.- Frequency (
Slide a fixed window of length `min_size` and count
Now the whole algorithm is one pass of a fixed-length window across
s:- A window of length
min_sizecan begin anywhere from offset0throughlen(s) - min_sizeinclusive, givingnum_windows = len(s) - min_size + 1windows. - Slice
window = s[start : start + min_size]and computedistinct_letters = len(set(window)). Sincemin_size <= 26, building this tiny set takesO(min_size)work. - Only when
distinct_letters <= max_lettersdo we incrementcounts[window]. - Finally, scan
counts.values()starting frombest_count = 0so an emptycountsdictionary cleanly returns0without crashing.
counts: Dict[str, int] = {} num_windows = len(s) - min_size + 1 for start in range(num_windows): window = s[start : start + min_size] distinct_letters = len(set(window)) if distinct_letters <= max_letters: counts[window] = counts.get(window, 0) + 1 best_count = 0 for count in counts.values(): if count > best_count: best_count = count- A window of length
Trace Example 1 step by step
Let's trace
s = "xyxzwxyxxyx",max_letters = 2,min_size = 3,max_size = 5(num_windows = 11 - 3 + 1 = 9):start window set(window) unique <= 2? counts update ----- ------ --------------- ------------ --------------------- 0 "xyx" {'x', 'y'} (2) YES counts["xyx"] = 1 1 "yxz" {'x', 'y', 'z'} (3) NO skipped 2 "xzw" {'w', 'x', 'z'} (3) NO skipped 3 "zwx" {'w', 'x', 'z'} (3) NO skipped 4 "wxy" {'w', 'x', 'y'} (3) NO skipped 5 "xyx" {'x', 'y'} (2) YES counts["xyx"] = 2 6 "yxx" {'x', 'y'} (2) YES counts["yxx"] = 1 7 "xxy" {'x', 'y'} (2) YES counts["xxy"] = 1 8 "xyx" {'x', 'y'} (2) YES counts["xyx"] = 3 counts = {"xyx": 3, "yxx": 1, "xxy": 1} --> best_count = 3Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_substring_occurrences( s: str, max_letters: int, min_size: int, max_size: int ) -> int: # Key insight: only windows of length `min_size` need to be checked. # Any longer valid substring of length L > min_size occurring k times starts # with its `min_size` prefix at all k positions, and that prefix uses a subset # of the same letters (so <= max_letters unique letters) -> >= k occurrences. # counts: maps valid substring text (e.g., "xyx") -> int occurrence count counts: Dict[str, int] = {} # Phase 1: Slide a fixed window of length `min_size` across every valid start index. # Using `len(s) - min_size + 1` includes the final window ending at `len(s)` and # counts overlapping occurrences automatically (one check per start index). num_windows = len(s) - min_size + 1 for start in range(num_windows): window = s[start : start + min_size] distinct_letters = len(set(window)) if distinct_letters <= max_letters: counts[window] = counts.get(window, 0) + 1 # Phase 2: Return the highest frequency among valid windows (0 if none qualified). best_count = 0 for count in counts.values(): if count > best_count: best_count = count return best_count✅ Submit now — all tests should pass.
Intuition & how it works
Imagine scanning a long book for the most repeated 3-to-5-word phrase that uses at most 2 unique words. Anytime a 4-word phrase like "go go stop go" appears, its opening 3 words "go go stop" automatically appear at that exact same starting spot—and dropping the 4th word can never add a new unique word! That means a longer valid substring can never appear more often than its own min_size prefix. Instead of testing every length up to max_size, we slide a single sliding window (a fixed-length frame of size min_size that moves one index at a time across the string) and tally each valid window inside a hash map (Python's dict, which stores substring -> count pairs in O(1) average lookup time).
Why do the naive approaches fail or waste work? Calling Python's built-in s.count(sub) gives wrong answers because it skips past each match and misses overlaps ("zzzzzz".count("zzzz") returns 1 instead of 3), while also re-scanning the entire string in O(n^2) time. Meanwhile, looping over every length from min_size to max_size creates up to 26 times as many string slices and dictionary entries even though lengths above min_size can never beat min_size.
Let's trace a concrete mini-example with s = "xxzxx", max_letters = 2, min_size = 2, and max_size = 3:
Only check windows of length min_size = 2:
start = 0: "xx" -> 1 unique letter (<= 2) -> counts["xx"] = 1
start = 1: "xz" -> 2 unique letters (<= 2) -> counts["xz"] = 1
start = 2: "zx" -> 2 unique letters (<= 2) -> counts["zx"] = 1
start = 3: "xx" -> 1 unique letter (<= 2) -> counts["xx"] = 2
Highest count in `counts` is 2 (from "xx" at offsets 0 and 3).
(Notice length-3 candidates "xxz", "xzx", "zxx" each appear only once!)
Complexity
Let n = len(s) be the string length and k = min_size (k <= 26).
- Time:
O(n * k)(which isO(n)sincek <= 26). There aren - k + 1start indices. At each index, slicings[start : start + k], buildingset(window), and hashingwindowintocountseach inspectkcharacters. Scanningcounts.values()at the end visits at mostn - k + 1entries inO(1)time each. - Space:
O(n * k)in the worst case. When every window of lengthkqualifies and is unique,countsholds up ton - k + 1string keys of lengthkeach. Becausek <= 26, memory grows linearly withn.
Edge cases
- No valid substring exists: In Example 3 (
s = "pqrstu",max_letters = 2,min_size = 4), every window has4unique letters, socountsstays empty andbest_count = 0is returned safely. - Overlapping identical runs: In Example 2 (
"zzzzzz"withmin_size = 4andmax_letters = 1),"zzzz"is counted at offsets0, 1, 2, returning3. min_size == len(s):num_windowsequals1, checking only the full stringsand returning1or0.max_letters >= min_size(ormax_letters == 26): A string of lengthmin_sizehas at mostmin_sizeunique characters, so every window qualifies.max_size > min_size: Safely ignored because every longer valid substring'smin_sizeprefix is also valid and occurs at least as many times.
Common mistakes
- Using
s.count(window)to count occurrences:str.countcounts non-overlapping matches only, returning1instead of3on Example 2 ("zzzzzz","zzzz"), and turns the loop into anO(n^2)scan that times out onn = 100,000. - Finding the most frequent window first and checking
max_letterssecond: On"abcabcabcaa"withmax_letters = 2andmin_size = 3,"abc"and"bca"occur 3 times each but use 3 unique letters; filtering before taking the maximum ensures invalid substrings cannot mask"caa"(count1). - Calling
max(counts.values())without a default: When no substring qualifies,countsis empty andmax(counts.values())raisesValueError: max() arg is an empty sequence. Initializebest_count = 0(or passdefault=0). - Off-by-one in the loop bound: Writing
range(len(s) - min_size)drops the final window starting atlen(s) - min_size; always include+ 1.
Alternative approaches
- Count all
min_sizewindows first, then filter keys: Incrementcounts[window]unconditionally during the scan and checklen(set(window)) <= max_letterswhile iterating overcounts.items(). Worst-caseO(n * k)time and space are identical; it callsset()fewer times when windows repeat heavily, at the cost of storing invalid keys incounts. - Sliding 26-letter frequency array + rolling hash: Maintain letter frequencies in a 26-slot array to update
distinct_lettersinO(1)per step, and represent each window with a rolling hash (a numeric fingerprint updated inO(1)time as one character leaves the window and one enters). That reduces runtime toO(n)independent ofk, though you must guard against a hash collision (two different substrings accidentally producing the same numeric hash) using double hashing or string verification. Fork <= 26, plain slicing is simpler and completely collision-free.
Follow-up questions
- How would you modify the function if it needed to return the most frequent valid substring itself, choosing the lexicographically smallest string on ties? That tie-breaker uses lexicographical order (standard dictionary order where
"aa"comes before"aab"and"ab"). Remarkably, the winning substring still has lengthmin_size: if a longer valid substringwtied for the top count, itsmin_sizeprefixphas at least the same count (so an equal count) and is strictly shorter, meaningp < win dictionary order! Simply track(best_count, best_word)acrosscounts.items(), updating whencount > best_countorcount == best_count and window < best_word. - What breaks if min_size is no longer bounded by 26—for example, min_size = 50,000 inside a 100,000-character string—and how can you keep the runtime linear? Slicing
window = s[start : start + min_size]would copy50,000characters50,001times (2.5 * 10^9character copies) and time out. Replace string slicing with a 26-slot sliding character counter fordistinct_lettersand a double polynomial rolling hash(h1, h2)as the dictionary key, bringing total time down toO(n)regardless ofmin_size. - How would you estimate or compute the top substring count if the input arrived as a multi-gigabyte character stream that cannot fit in memory? Keep only the last
min_sizecharacters in a small ring buffer to emit valid windows on the fly. For exact counts across a cluster, hash each valid window to one ofMworker machines so identical windows always land on the same worker, then take the max across workers; on a single memory-constrained machine, use a heavy-hitters sketch (a fixed-size approximate frequency table such as Count-Min Sketch or Misra-Gries that estimates top frequencies within a guaranteed error bound).
Follow-up questions
- How would you modify the function if it needed to return the most frequent valid substring itself, choosing the lexicographically smallest string on ties?
- What breaks if min_size is no longer bounded by 26—for example, min_size = 50,000 inside a 100,000-character string—and how can you keep the runtime linear?
- How would you estimate or compute the top substring count if the input arrived as a multi-gigabyte character stream that cannot fit in memory?
Similar questions
- Valid Course Schedule Ordering
- Live Median Queries Over a Growing Integer Stream
- Smallest Value Meeting a Suffix Frequency Threshold
- Framing Length-Prefixed Packets from Async Byte Chunks
- Reconstruct Payload Strings from Tag-Linked Fragments
- Partition Words into Canonical Anagram Buckets
More Microsoft interview questions
- In-Memory Cache With LRU Eviction Medium
- Threshold-Sweep Precision-Recall Curve Easy
- Distinct Triplets Summing to Zero Medium Pro
- Longest Duplicate-Free Substring Length Medium Pro
- Consolidate Overlapping Intervals Medium Pro
- Minimum Highway Fuel Expense Medium Pro
- Smallest Daily Cargo Vessel Capacity Medium Pro
- Evaluating Binary Classifiers Under Unequal Error Costs Medium Pro
- Sequential Markdowns and Undiscounted Indices Hard Pro
- Worldwide Mobile 1-on-1 VoIP Calling Architecture Medium Pro