Topics

The problem asks us to calculate the sum of scores of all substrings of a given string. Score of a string is the number of unique characters present in the string.

Example string = “aac”
Substring and score = (“a”,1), (“aa”,0), (“aac”,1), (“a”,1), (“ac”,2), (“c”,1)
Total score = 6

Idea

Instead of iterating through all substrings, we iterate through each position in the original string and calculate its contribution to the total score. This approach focuses on how many substrings are “influenced” by each position in the string.

To implement this efficiently, we precompute two arrays, lpos and rpos. For each index , lpos[i] stores the index of the last occurrence of character before index (or -1 if no such occurrence exists). Similarly, rpos[i] stores the index of the next occurrence of after index (or if no such occurrence). These arrays can be computed in linear time using forward and backward scans. The contribution of each index to the total score is then calculated:

This is because this char will contribute 1 to substrings where it’s unique, i.e substrings whose start position is in range and end position is in range . Basic counting subarrays yields us the above product. Summing these contributions for all indices from 0 to gives the final answer.

Time Complexity: per test case.

Code

int solve(int n, string s) {
    // Stores last seen position of each char (A-Z)
    vector<int> pos(26, -1);
 
    vector<int> lpos(n);
    vector<int> rpos(n);
 
    for (int i = 0; i < n; ++i) {
        int char_value = s[i] - 'A';
        lpos[i] = pos[char_value];
        pos[char_value] = i;
    }
 
    // Reset for right-to-left pass
    fill(all(pos), n);
 
    for (int i = n - 1; i >= 0; --i) {
        int char_value = s[i] - 'A';
        rpos[i] = pos[char_value];
        pos[char_value] = i;
    }
 
    ll result = 0;
    for (int i = 0; i < n; ++i) {
        int distance_to_prev = i - lpos[i];
        int distance_to_next = rpos[i] - i;
        result += (1LL * distance_to_prev * distance_to_next);
    }
 
    return result;
}