Maximum Number of Occurrences of a Substring - Problem
Maximum Number of Occurrences of a Substring
You're given a string
π Size constraint: The substring length must be between
π€ Character constraint: The substring must contain at most
Goal: Return the highest frequency count among all valid substrings. If no valid substring exists, return 0.
Example: For string
You're given a string
s and three constraints: maxLetters, minSize, and maxSize. Your task is to find the maximum number of occurrences of any substring that satisfies all the following rules:π Size constraint: The substring length must be between
minSize and maxSize (inclusive)π€ Character constraint: The substring must contain at most
maxLetters unique charactersGoal: Return the highest frequency count among all valid substrings. If no valid substring exists, return 0.
Example: For string
"aababcaab" with maxLetters=2, minSize=3, maxSize=4, the substring "aab" appears 2 times and satisfies both constraints. Input & Output
example_1.py β Basic Case
$
Input:
s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
βΊ
Output:
2
π‘ Note:
The substring "aab" appears 2 times at positions 1-3 and 6-8. It has exactly 2 unique characters ('a' and 'b'), satisfying maxLetters=2 constraint.
example_2.py β No Valid Substrings
$
Input:
s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
βΊ
Output:
2
π‘ Note:
The substring "aaa" appears 2 times (positions 0-2 and 1-3). It has only 1 unique character, satisfying all constraints.
example_3.py β Complex Case
$
Input:
s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3
βΊ
Output:
0
π‘ Note:
No substring of length 3 has β€ 2 unique characters. All 3-character substrings have exactly 3 unique characters, violating the maxLetters=2 constraint.
Constraints
- 1 β€ s.length β€ 105
- 1 β€ maxLetters β€ 26
- 1 β€ minSize β€ maxSize β€ min(26, s.length)
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Understand constraints
Pattern must be minSize-maxSize long with β€maxLetters unique characters
2
Key insight discovery
Realize shorter patterns appear at least as often as longer ones
3
Sliding window
Check only minimum length patterns using sliding window
4
Count and compare
Track frequencies and return the maximum
Key Takeaway
π― Key Insight: The optimal solution leverages the mathematical property that shorter substrings appear at least as frequently as longer ones, allowing us to focus only on minimum-length patterns for maximum efficiency.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code