Total Appeal of A String - Problem
The appeal of a string is defined as the number of distinct characters found in that string. Think of it as measuring how "diverse" a string is in terms of its character variety.
For example:
- The appeal of
"abbca"is 3 because it contains 3 distinct characters:'a','b', and'c' - The appeal of
"aaa"is 1 because it only contains the character'a' - The appeal of
"abc"is 3 because all characters are distinct
Your task is to find the total appeal of all possible substrings of a given string s. A substring is any contiguous sequence of characters within the original string.
This means you need to:
- Generate all possible substrings of the input string
- Calculate the appeal (distinct character count) for each substring
- Sum up all these appeal values
Goal: Return the sum of appeals of all substrings of the given string.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "abbca"
โบ
Output:
28
๐ก Note:
The string 'abbca' has substrings like 'a'(1), 'ab'(2), 'abb'(2), 'abbc'(3), 'abbca'(3), 'b'(1), 'bb'(1), 'bbc'(2), 'bbca'(3), etc. When we sum the appeal (distinct character count) of all 15 substrings, we get 28.
example_2.py โ Single Character
$
Input:
s = "abc"
โบ
Output:
10
๐ก Note:
Substrings: 'a'(1), 'ab'(2), 'abc'(3), 'b'(1), 'bc'(2), 'c'(1). Total appeal = 1+2+3+1+2+1 = 10.
example_3.py โ Repeated Characters
$
Input:
s = "aaaa"
โบ
Output:
10
๐ก Note:
All substrings contain only the character 'a', so each has appeal 1. There are 10 total substrings: 4 of length 1, 3 of length 2, 2 of length 3, and 1 of length 4. Total = 4ร1 + 3ร1 + 2ร1 + 1ร1 = 10.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize tracking variables
Set up total_appeal=0, current_appeal=0, and last_occurrence map
2
Process each character
For each position, calculate how many new substrings this character contributes to
3
Calculate contribution
contribution = current_index - last_occurrence_index
4
Update running totals
Add contribution to current_appeal, then add current_appeal to total
Key Takeaway
๐ฏ Key Insight: Instead of generating O(nยฒ) substrings, we calculate how each character contributes to all substrings ending at each position. This transforms the problem from O(nยณ) brute force to O(n) optimal solution by leveraging the mathematical relationship between character positions and their contributions.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, constant time operations for each character
โ Linear Growth
Space Complexity
O(k)
O(k) where k is the number of distinct characters (at most 26 for lowercase letters)
โ Linear Space
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Time limit: The solution must run efficiently for large inputs
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code