KatInterview

Peak Occurrence Count of a Bounded Substring

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringssliding-windowhash-mapstrings

Last 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 in s.
  • 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 L satisfies low <= L <= high and the number of distinct characters in it is at most limit.
  • Return the largest occurrence count across all qualifying substrings. Substrings of different lengths compete together for the same maximum.
  • Return 0 when no substring qualifies — for instance, when low exceeds len(s).

Constraints

  • 1 <= len(s) <= 10^5
  • s consists only of lowercase English letters 'a'–'z'.
  • 1 <= low <= high <= 26
  • 1 <= limit <= 26. When limit is 26, 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.