Peak Occurrence Count of a Bounded Substring
StringsAuto-graded · 26 test casesLast updated
Tests whether a candidate can reduce a multi-length sliding-window problem to a single window size and efficiently track distinct-character counts.
Given a string s, examine every substring whose length falls between low and high (inclusive) and that contains no more than limit distinct characters. Return the highest number of times any single qualifying substring appears in s.
Rules
- A substring is a contiguous sequence of characters from
s. Two substrings are considered the same if and only if they consist of the same characters in the same order, regardless of where they appear ins. - Occurrences are counted by starting position, so overlapping matches are each counted. For example,
"aa"appears 2 times in"aaa"(starting at index 0 and index 1). - A substring qualifies when its length
Lsatisfieslow <= L <= highand the number of distinct characters in it is at mostlimit. - Return the largest occurrence count across all qualifying substrings. Substrings of different lengths compete together for the same maximum.
- Return
0when no substring qualifies — for instance, whenlowexceedslen(s).
Constraints
1 <= len(s) <= 10^5sconsists only of lowercase English letters'a'–'z'.1 <= low <= high <= 261 <= limit <= 26. Whenlimitis26, the distinct-character filter never excludes anything.
Examples
Example 1
Input: peak_substring_frequency('abcde', 2, 4, 26)
Output: 1
Example 2
Input: peak_substring_frequency('aaaba', 2, 3, 1)
Output: 2
Example 3
Input: peak_substring_frequency('abab', 2, 3, 1)
Output: 0
Hints
Hint 1
Consider what happens to the frequency of a longer qualifying substring when you trim it down to exactly `low` characters — does the prefix still qualify, and does it appear at least as often?
Hint 2
You only need to count substrings of one specific length. Slide a fixed-width window across `s` and maintain the count of distinct letters inside it incrementally in O(1) per step.
Hint 3
Use a dictionary keyed by window text to accumulate occurrence counts. Guard against calling max() on an empty dictionary, and remember to handle the case where `low > len(s)` before the loop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Insight: Only the Minimum Length Matters
The length range [low, high] looks like it requires checking every length separately, but it does not. Consider any qualifying substring T with length greater than low. Let P be its first low characters:
Palso qualifies. Its length is exactlylow, which is in range. A prefix cannot introduce more distinct characters than the full string, soPhas at mostlimitdistinct characters.Poccurs at least as often asT. Every starting position ofTis also a starting position ofP.
Therefore, for any longer qualifying substring, a qualifying length-low substring matches or beats its occurrence count. The maximum is always achieved at length low, making high irrelevant to the answer.
Algorithm
Slide a fixed window of width L = low across s:
- Maintain a 26-element count array and an integer
distinctto track how many letters currently appear in the window. Both update in O(1) per step. - Whenever the window has reached full size and
distinct <= limit, slice the window text and increment its entry in a frequency dictionary. - Return the largest value in the dictionary, or
0if it is empty.
Correctness
- Reduction: As argued, restricting to length
Lsubstrings does not miss the maximum. - Incremental distinct tracking:
distinctrises when a letter's count goes from 0 to 1, and falls when it drops from 1 to 0, so it is always exact. - Overlap counting: Every starting position is visited exactly once, so overlapping occurrences are all captured naturally.
- Edge cases: If
low > len(s)there are no valid windows and we return0immediately. If every window fails the distinct-character test the dictionary stays empty and we return0.
Complexity
Let n = len(s) and L = low (with L <= 26).
- Time: O(n · L). Window updates are O(1); slicing and hashing a window costs O(L). Since
L <= 26, this is at most ~2.6 million character operations forn = 10^5. - Space: O(n · L) in the worst case when all windows are distinct (each key stores
Lcharacters). The count array is O(26).
For a strict O(n) solution a rolling hash could replace the string slice, but for L <= 26 the above is fast enough in practice.
Reference Solution
def peak_substring_frequency(s: str, low: int, high: int, limit: int) -> int:
n = len(s)
L = low
if L > n:
return 0
# Any qualifying substring longer than L has a length-L prefix that also
# qualifies (a prefix can only have fewer or equal distinct chars) and
# appears at least as often. So the maximum is always achieved at length L;
# the `high` parameter cannot change the answer.
cnt = [0] * 26 # per-letter counts inside the current window
distinct = 0 # number of distinct letters currently in the window
freq = {} # window text -> total occurrence count
for i in range(n):
# Expand: bring s[i] into the window.
c = ord(s[i]) - 97
if cnt[c] == 0:
distinct += 1
cnt[c] += 1
# Shrink: evict s[i - L] once the window would exceed length L.
if i >= L:
d = ord(s[i - L]) - 97
cnt[d] -= 1
if cnt[d] == 0:
distinct -= 1
# Record the window once it has reached full length L.
if i >= L - 1 and distinct <= limit:
sub = s[i - L + 1:i + 1]
freq[sub] = freq.get(sub, 0) + 1
return max(freq.values()) if freq else 0