1211. Repeated Letter Tally

Hard7.5 points estimatedCountingStringCombinatorics

A linguist scores every fragment of a transcript by how many different letters show up in it more than once. Given a string s of lowercase letters, consider every non-empty substring (substrings at different positions are different even if their text matches). The echo score of a substring is the number of distinct letters that occur at least twice inside it. For abab the substring aba scores 1 (only a repeats) and the whole string scores 2.

Return the sum of the echo scores over all substrings as a long. Checking each substring would take quadratic time; aim for O(n) time and O(n) space by counting, for each position, how many substrings it contributes to.

Example 1

Input:
s = "aab"
Output:
2
Explanation:

Only aa and aab contain a repeated letter (a), each scoring 1, so the answer is 2.

Example 2

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

Substrings aba and bab score 1 each and the whole abab scores 2, so the answer is 4.

Example 3

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

No letter repeats inside any substring, so the answer is 0.

Constraints

1 ≤ s.length ≤ 105

s contains only 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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 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…