1287. Capped Letter Substrings

Medium3.5 points estimatedSliding WindowStringHash TableCounting

A writing tool flags passages that lean too hard on a single letter. You are given a string s of lowercase letters and an integer cap. Call a non-empty substring tidy when no letter occurs in it more than cap times. Return how many tidy substrings s has. Substrings are counted by position, so equal substrings taken from different places are counted separately. The result can be larger than a 32-bit integer, so return it as a 64-bit integer.

Aim for O(n) time and O(1) extra space, where n is the length of s: grow a window to the right and shrink it from the left whenever the newest letter pushes its own count above cap.

Example 1

Input:
s = "aab", cap = 1
Output:
4
Explanation:

The tidy substrings are a, a, b and ab; both 'aa' and 'aab' hold two copies of a, so the answer is 4.

Example 2

Input:
s = "aaaa", cap = 2
Output:
7
Explanation:

Every substring of length 1 or 2 is tidy (4 + 3), while any longer one holds three equal letters, so there are 7.

Example 3

Input:
s = "abcabc", cap = 1
Output:
15
Explanation:

With cap 1 the tidy substrings are those with all different letters, which means lengths up to 3: 6 + 5 + 4 = 15.

Constraints

1 ≤ s.length ≤ 2 * 105

1 ≤ cap ≤ s.length

s consists of lowercase 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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(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…