1315. Bounded Frequency Stretch

A radio station logs the first letter of every song title it plays in the string s. A producer wants a stretch of consecutive plays that feels balanced: every letter that shows up in the stretch must appear at least lo times and at most hi times. Letters that never appear in the stretch are ignored.

Return the length of the longest substring of s that is balanced in this sense, or 0 if no substring is. Note that a letter appearing fewer than lo times in a stretch makes that stretch invalid, even if the letter appears only once.

Because only 26 letters exist, try each possible number of distinct letters from 1 to 26 and run a window for it, shrinking from the left whenever the window holds too many distinct letters or a letter above hi. The intended solution runs in O(26 * n) time and O(1) extra space.

Example 1

Input:
s = "aabbbc", lo = 2, hi = 3
Output:
5
Explanation:

The substring "aabbb" has two a letters and three b letters, both within [2, 3], and adding the single c would break the lower bound, so the answer is 5.

Example 2

Input:
s = "abc", lo = 2, hi = 2
Output:
0
Explanation:

No letter appears twice anywhere, so no substring is balanced and the answer is 0.

Example 3

Input:
s = "aaaa", lo = 1, hi = 3
Output:
3
Explanation:

The whole string has four a letters, which is above 3, so the best balanced substring has length 3.

Constraints

  • 1 ≤ s.length ≤ 5 * 104

  • 1 ≤ lo ≤ hi ≤ s.length

  • s consists of lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(26 * n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…