Problem Description
Given a string s, each substring’s appeal is defined as the number of distinct characters within it. The goal is to compute the total appeal for all possible contiguous substrings of s.
Key Insights
- Brute force enumeration of all substrings is too slow given the constraints.
- Rather than computing distinct counts for each substring independently, we can count each character’s contribution to the total appeal.
- For every character at position i, its contribution to all substrings ending at i can be determined by the distance from its last occurrence.
- Use a dynamic programming approach where we maintain a running sum of the appeals of substrings ending at each index.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string
Space Complexity: O(1) (using an array of fixed size 26 for tracking last occurrences)
Solution
The solution leverages the following idea: as you iterate through the string, track the last occurrence index for each character. For each position i, the additional appeal provided by the character s[i] is (i - lastOccurrence[s[i]]). This value represents how many new substrings ending at position i include s[i] as a new distinct character (since its previous occurrence). A running sum (currentAppeal) is maintained for substrings ending at each position, and the overall total is updated accordingly. This eliminates the need for explicit substring generation.