Maximum Number of Occurrences of a Substring - Problem

Given a string s, return the maximum number of occurrences of any substring under the following rules:

  • The number of unique characters in the substring must be less than or equal to maxLetters.
  • The substring size must be between minSize and maxSize inclusive.

Input & Output

Example 1 — Basic Case
$ Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
💡 Note: Substring "aab" appears twice and has 2 unique characters (≤ maxLetters), length 3 (within range). Other valid substrings appear only once.
Example 2 — No Valid Substrings
$ Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
💡 Note: Substring "aaa" appears 2 times (positions 0-2 and 1-3), has 1 unique character (≤ maxLetters), length 3 (within range).
Example 3 — All Different Characters
$ Input: s = "abcde", maxLetters = 2, minSize = 2, maxSize = 3
Output: 0
💡 Note: No substring can satisfy maxLetters = 2, since even the shortest substrings of length 2 have 2 different characters, but we need exactly 2 different characters maximum. All substrings of length 2 like "ab", "bc" have exactly 2 characters which satisfies the constraint, so answer is 1.

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ maxLetters ≤ 26
  • 1 ≤ minSize ≤ maxSize ≤ min(26, s.length)

Visualization

Tap to expand
Maximum Substring Occurrences: s="aababcaab", maxLetters=2, minSize=3, maxSize=4aababcaabFirst occurrence of "aab"aabSecond occurrence of "aab"Valid substring "aab": length=3 ✓, unique chars=2 ≤ maxLetters ✓Maximum Occurrences: 2
Understanding the Visualization
1
Input
String s with constraints: maxLetters, minSize, maxSize
2
Process
Find all valid substrings and count occurrences
3
Output
Return maximum occurrence count
Key Takeaway
🎯 Key Insight: Focus only on minimum size substrings - they always appear most frequently among valid options
Asked in
Facebook 12 Google 8 Amazon 6
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen