1266. Even-Handed Substrings

A radio operator logs a stream of tone signals, each one of three tones written a, b or c, in the string s. A non-empty contiguous piece of the log is even-handed when every tone that appears in it appears the same number of times: aabb, ccc and abcabc are even-handed, while aab is not. A tone that does not appear at all is ignored.

Return how many non-empty substrings of s are even-handed. Substrings at different positions count separately. The answer can exceed 32 bits, so return it as a 64-bit integer.

Aim for O(n) expected time and O(n) extra space; checking every substring is too slow for 100,000 tones.

Example 1

Input:
s = "aabb"
Output:
8
Explanation:

The even-handed substrings are a, a, b, b, aa, bb, ab and aabb, so the answer is 8.

Example 2

Input:
s = "abc"
Output:
6
Explanation:

The single tones a, b, c, the pieces ab and bc, and the whole string abc are even-handed, giving 6.

Example 3

Input:
s = "abab"
Output:
8
Explanation:

The four single tones, the pieces ab, ba and ab, and the whole string abab are even-handed, giving 8.

Constraints

1 ≤ s.length ≤ 105

s consists only of the letters a, b and c.

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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n)
Space
O(n)

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…