Maximum Number of Occurrences of a Substring — LeetCode 1297 Python Solution

MediumHash TableStringSliding Window
Problem
#1297
Reading time
2 min

The 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.

Example

Input
s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output
2
Explanation
Substring "aab" has 2 occurrences in the original string.

Python solution

Python
class Solution:
    def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
        ans = 0
        cnt = Counter()
        for i in range(len(s) - minSize + 1):
            t = s[i : i + minSize]
            ss = set(t)
            if len(ss) <= maxLetters:
                cnt[t] += 1
                ans = max(ans, cnt[t])
        return ans

Complexity

MeasureComplexity
TimeO(n \times m)
SpaceO(n \times m) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1297. Maximum Number of Occurrences of a Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1297. Maximum Number of Occurrences of a Substring?
LeetCode 1297. Maximum Number of Occurrences of a Substring is rated Medium on LeetCode.
What is the time complexity of LeetCode 1297. Maximum Number of Occurrences of a Substring?
The Python solution on this page runs in O(n \times m).
What is the space complexity of LeetCode 1297. Maximum Number of Occurrences of a Substring?
The Python solution on this page uses O(n \times m) auxiliary space.
What topics does LeetCode 1297. Maximum Number of Occurrences of a Substring cover?
LeetCode 1297. Maximum Number of Occurrences of a Substring is tagged Hash Table, String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview