#1297
Maximum Number of Occurrences of a Substring
MediumHash TableStringSliding WindowHash MapSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a sliding window approach to efficiently count valid substrings of fixed length while maintaining a count of unique characters. This reduces the need to generate all substrings explicitly.
⚙️
Algorithm
5 steps- 1Step 1: Use a sliding window of size minSize to traverse the string.
- 2Step 2: Maintain a frequency map of characters in the current window and a count of unique characters.
- 3Step 3: For each new character added to the window, update the frequency map and unique character count.
- 4Step 4: If the unique character count exceeds maxLetters, shrink the window from the left until it is valid again.
- 5Step 5: Count occurrences of valid substrings and keep track of the maximum count.
solution.py19 lines
1def maxFreq(s, maxLetters, minSize, maxSize):
2 from collections import defaultdict
3 count = defaultdict(int)
4 n = len(s)
5 freq = defaultdict(int)
6 unique_count = 0
7 left = 0
8 for right in range(n):
9 if freq[s[right]] == 0:
10 unique_count += 1
11 freq[s[right]] += 1
12 if right - left + 1 > minSize:
13 freq[s[left]] -= 1
14 if freq[s[left]] == 0:
15 unique_count -= 1
16 left += 1
17 if right - left + 1 == minSize and unique_count <= maxLetters:
18 count[s[left:right + 1]] += 1
19 return max(count.values(), default=0)ℹ
Complexity note: The time complexity is O(n) because we traverse the string once with the sliding window technique. The space complexity is O(n) due to the frequency map storing characters and their counts.
- 1Sliding window technique is efficient for fixed-length substring problems.
- 2Maintaining a frequency map helps track character counts and unique characters.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.