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: 1
💡 Note: Substrings of length 2: "ab", "bc", "cd", "de" each have exactly 2 unique characters (≤ maxLetters), and each appears once. Maximum count is 1.

Constraints

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

Visualization

Tap to expand
Maximum Number of Occurrences of a Substring INPUT String s: a a b a b c a a b 0 1 2 3 4 5 6 7 8 Parameters: maxLetters = 2 minSize = 3 maxSize = 4 Valid Substrings (size=3): "aab" - 2 unique [OK] "aba" - 2 unique [OK] "bab" - 2 unique [OK] "abc" - 3 unique [SKIP] ALGORITHM STEPS 1 Focus on minSize Only Longer valid substrings contain shorter ones 2 Sliding Window Extract all substrings of length minSize=3 3 Check Unique Chars Only count if unique chars <= maxLetters 4 Count with HashMap Track frequency and find maximum count HashMap Counts: "aab" : 2 "aba" : 1 "bab" : 1 "caa" : 1 FINAL RESULT Most frequent valid substring: "aab" Found at positions: a a b a b c a a b Position 0-2 (1st occurrence) a a b a b c a a b Position 6-8 (2nd occurrence) Output: 2 Key Insight: We only need to check substrings of minSize because any longer valid substring must contain a shorter valid substring. If a longer string appears N times, its minSize prefix also appears at least N times. Time: O(n * minSize), Space: O(n * minSize) for the hashmap. TutorialsPoint - Maximum Number of Occurrences of a Substring | Optimized - Focus on Minimum Size
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