Problem Description
Given an uppercase English string s, compute the sum of unique characters count across all of its substrings. For a substring t, countUniqueChars(t) returns the number of characters which appear exactly once in t. Note that even if some substrings are identical, they are considered separately in the sum.
Key Insights
- Instead of evaluating each substring (which is too slow for s.length up to 10^5), compute the contribution of each character to the final answer.
- For every occurrence of character c at index i, determine the number of substrings where this occurrence is the unique instance of c.
- Use the idea of "contribution":
- Let prev be the index of the previous occurrence of the same character (or -1 if none).
- Let next be the index of the next occurrence of the same character (or s.length if none).
- Then, the number of substrings that include s[i] as the only occurrence of that character is (i - prev) * (next - i).
- Sum these contributions for all characters in s.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution uses a mathematical insight. Iterate through the string while tracking the previous and next occurrence indexes for each character. For every occurrence at index i, calculate its contribution by finding the distance to the previous occurrence and the distance to the next occurrence. Multiply these two distances to determine in how many substrings s[i] can be the unique instance of that character and sum the results. This eliminates the need to generate all substrings explicitly.