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:

  1. min_size <= len(w) <= max_size
  2. w contains no more than max_letters unique 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 length 3 (within [3, 5]) and uses 2 unique letters ('x' and 'y'). It begins at offsets 0, 5, and 8, giving frequency 3. Windows containing 'z' or 'w' alongside 'x' and 'y' use 3 unique letters and are invalid, while no valid substring of length 3, 4, or 5 appears more than 3 times.

Example 2

  • Input: s = "zzzzzz", max_letters = 1, min_size = 4, max_size = 5
  • Output: 3
  • Explanation: Substring "zzzz" uses 1 unique letter and begins at overlapping offsets 0, 1, and 2 (3 total occurrences), beating "zzzzz" which begins only at offsets 0 and 1.

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 length 4 or longer contains at least 4 unique letters, exceeding max_letters = 2.

Constraints

  • 1 <= len(s) <= 10^5
  • Every character of s is a lowercase English letter ('a'–'z').
  • 1 <= max_letters <= 26
  • 1 <= min_size <= max_size <= min(26, len(s))

Step-by-step walkthrough

  1. Understand what makes a substring valid

    We want the peak frequency among all valid substrings of s, where a substring w qualifies when:

    1. its length satisfies min_size <= len(w) <= max_size, and
    2. it uses at most max_letters unique 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.

  2. Why checking every allowed length does unnecessary work

    A direct brute-force solution loops over every allowed length L from min_size to max_size, slices every substring of length L, checks len(set(w)) <= max_letters, and tallies counts in a dictionary.

    Because max_size <= 26, that brute force inspects up to 26 * 100,000 = 2.6 * 10^6 substrings 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.

  3. Key insight: why length `min_size` always wins (or ties)

    Suppose some longer valid substring w of length L > min_size occurs k times in s. Look at p, the prefix made of the first min_size characters of w:

    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 p against w on every condition:

    1. Frequency (count(p) >= count(w)): Wherever w begins at offset i, p also begins at offset i (and p might appear at extra offsets too).
    2. Unique letters (unique(p) <= unique(w) <= max_letters): Every character of p is already inside w, so dropping the tail can only keep or shrink the set of unique letters—never enlarge it.
    3. Length (len(p) == min_size): min_size always lies within [min_size, max_size].

    Therefore, every longer valid substring is matched or beaten by its own min_size prefix! We only ever need to examine substrings of length min_size; max_size never changes the answer.

  4. 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_size can begin anywhere from offset 0 through len(s) - min_size inclusive, giving num_windows = len(s) - min_size + 1 windows.
    • Slice window = s[start : start + min_size] and compute distinct_letters = len(set(window)). Since min_size <= 26, building this tiny set takes O(min_size) work.
    • Only when distinct_letters <= max_letters do we increment counts[window].
    • Finally, scan counts.values() starting from best_count = 0 so an empty counts dictionary cleanly returns 0 without 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
    
  5. 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 = 3
    
  6. Complete 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 is O(n) since k <= 26). There are n - k + 1 start indices. At each index, slicing s[start : start + k], building set(window), and hashing window into counts each inspect k characters. Scanning counts.values() at the end visits at most n - k + 1 entries in O(1) time each.
  • Space: O(n * k) in the worst case. When every window of length k qualifies and is unique, counts holds up to n - k + 1 string keys of length k each. Because k <= 26, memory grows linearly with n.

Edge cases

  • No valid substring exists: In Example 3 (s = "pqrstu", max_letters = 2, min_size = 4), every window has 4 unique letters, so counts stays empty and best_count = 0 is returned safely.
  • Overlapping identical runs: In Example 2 ("zzzzzz" with min_size = 4 and max_letters = 1), "zzzz" is counted at offsets 0, 1, 2, returning 3.
  • min_size == len(s): num_windows equals 1, checking only the full string s and returning 1 or 0.
  • max_letters >= min_size (or max_letters == 26): A string of length min_size has at most min_size unique characters, so every window qualifies.
  • max_size > min_size: Safely ignored because every longer valid substring's min_size prefix is also valid and occurs at least as many times.

Common mistakes

  • Using s.count(window) to count occurrences: str.count counts non-overlapping matches only, returning 1 instead of 3 on Example 2 ("zzzzzz", "zzzz"), and turns the loop into an O(n^2) scan that times out on n = 100,000.
  • Finding the most frequent window first and checking max_letters second: On "abcabcabcaa" with max_letters = 2 and min_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" (count 1).
  • Calling max(counts.values()) without a default: When no substring qualifies, counts is empty and max(counts.values()) raises ValueError: max() arg is an empty sequence. Initialize best_count = 0 (or pass default=0).
  • Off-by-one in the loop bound: Writing range(len(s) - min_size) drops the final window starting at len(s) - min_size; always include + 1.

Alternative approaches

  • Count all min_size windows first, then filter keys: Increment counts[window] unconditionally during the scan and check len(set(window)) <= max_letters while iterating over counts.items(). Worst-case O(n * k) time and space are identical; it calls set() fewer times when windows repeat heavily, at the cost of storing invalid keys in counts.
  • Sliding 26-letter frequency array + rolling hash: Maintain letter frequencies in a 26-slot array to update distinct_letters in O(1) per step, and represent each window with a rolling hash (a numeric fingerprint updated in O(1) time as one character leaves the window and one enters). That reduces runtime to O(n) independent of k, though you must guard against a hash collision (two different substrings accidentally producing the same numeric hash) using double hashing or string verification. For k <= 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 length min_size: if a longer valid substring w tied for the top count, its min_size prefix p has at least the same count (so an equal count) and is strictly shorter, meaning p < w in dictionary order! Simply track (best_count, best_word) across counts.items(), updating when count > best_count or count == 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 copy 50,000 characters 50,001 times (2.5 * 10^9 character copies) and time out. Replace string slicing with a 26-slot sliding character counter for distinct_letters and a double polynomial rolling hash (h1, h2) as the dictionary key, bringing total time down to O(n) regardless of min_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_size characters in a small ring buffer to emit valid windows on the fly. For exact counts across a cluster, hash each valid window to one of M worker 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

Similar questions

More Microsoft interview questions

All 252 Microsoft questions →