1195. Three-Way Even Stretches

Medium3.5 points estimatedHash TablePrefix SumCountingString

A lab logs each reading as a, b or c. A stretch of consecutive readings is called even when it contains the same number of a's, b's and c's. Given s, count the non-empty substrings that are even, counting each position range separately even when two ranges spell the same text.

Return the count as a long. For example abcabc has 5 such substrings. Two prefixes bound an even stretch exactly when the pair (count of a minus count of b, count of b minus count of c) is the same for both, with the empty prefix included.

Key every prefix on that pair and add the number of earlier prefixes with the same key, using a hash map for about O(n) time (or sorting the keys for O(n log n)) and O(n) space.

Example 1

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

The whole string has one of each letter.

Example 2

Input:
s = "aabbcc"
Output:
1
Explanation:

Only the whole string has equal counts of 2 each.

Example 3

Input:
s = "abcabc"
Output:
5
Explanation:

The substrings abc at 0, bca at 1, cab at 2, abc at 3 and the full string all balance.

Constraints

1 ≤ s.length ≤ 2 * 105

s contains only '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 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 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…