Maximum Number of Occurrences of a Substring Problem
Description
LeetCode Problem 1297.
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
minSizeandmaxSizeinclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 occurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
Constraints:
1 <= s.length <= 10^51 <= maxLetters <= 261 <= minSize <= maxSize <= min(26, s.length)sconsists of only lowercase English letters.
Solution
Approach: Only Count Substrings of Length minSize
maxSize turns out not to matter. Suppose a valid substring t longer than minSize occurs c times. Its first minSize letters form a substring t' that occurs at least at the same c places, and t' is valid too: it is long enough, and it has no more distinct letters than t. So the best count is always achieved by some substring of length exactly minSize.
Slide a window of length minSize over s. Keep the letter counts inside the window and the number of distinct letters, updating them as one letter enters and one leaves. Whenever the window has at most maxLetters distinct letters, add the window's text to a hash map of counts and update the maximum. Overlapping occurrences are counted, as Example 2 ("aaa" twice in "aaaa") requires.
Complexity: O(n · minSize) time and space, since each of the n windows is copied into the hash map as a string of length minSize (at most 26).
from collections import Counter
class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
# Every occurrence of a longer valid substring contains an occurrence of its
# first minSize letters, which is valid too, so only length minSize matters.
freq = Counter()
letters = Counter() # letter counts in the window s[i - minSize + 1 .. i]
best = 0
for i, ch in enumerate(s):
letters[ch] += 1
if i >= minSize:
out = s[i - minSize]
letters[out] -= 1
if letters[out] == 0:
del letters[out]
if i >= minSize - 1 and len(letters) <= maxLetters:
t = s[i - minSize + 1:i + 1]
freq[t] += 1
best = max(best, freq[t])
return best