Ctrl K

Most Frequent Short Fragment

Medium
You are given a string text and three integers max_distinct, min_len and max_len. A fragment is a non-empty run of consecutive characters of the string. A fragment is allowed when: - its length is at least min_len and at most max_len; - it contains at most max_distinct different letters. Find the allowed fragment that occurs in text the most times and return how many times it occurs. Occurrences may overlap. If no fragment is allowed, return 0.
Example 1
text='abcabcab', max_distinct=3, min_len=2, max_len=3 → 3

The fragment "ab" occurs three times (starting at 0, 3 and 6), and no other allowed fragment occurs more often.

Example 2
text='zzzzz', max_distinct=1, min_len=2, max_len=4 → 4

"zz" starts at positions 0, 1, 2 and 3; occurrences may overlap, so the answer is 4.

Example 3
text='abcd', max_distinct=1, min_len=2, max_len=2 → 0

Every fragment of length 2 has two different letters while only one is allowed, so no fragment qualifies.

Constraints
  • 1 ≤ len(text) ≤ 3·10⁵
  • text consists of lowercase English letters only
  • 1 ≤ max_distinct ≤ 26
  • 1 ≤ min_len ≤ max_len ≤ min(26, len(text))
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Repeat-Free Stretch MediumTwo-Letter Stretch MediumRecurring Gene Windows MediumWindow with Few Kinds of Letters MediumEvery Letter at Least k Times Medium
loading Python…
Input
text='abcabcab', max_distinct=3, min_len=2, max_len=3
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.