Total Appeal of A String - Problem

The appeal of a string is the number of distinct characters found in the string.

For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.

Given a string s, return the total appeal of all of its substrings.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abbca"
Output: 28
💡 Note: All substrings: "a"(1), "ab"(2), "abb"(2), "abbc"(3), "abbca"(3), "b"(1), "bb"(1), "bbc"(2), "bbca"(3), "b"(1), "bc"(2), "bca"(3), "c"(1), "ca"(2), "a"(1). Sum = 28
Example 2 — Single Character
$ Input: s = "z"
Output: 1
💡 Note: Only one substring "z" with appeal 1
Example 3 — All Same
$ Input: s = "aaa"
Output: 6
💡 Note: Substrings: "a"(1), "aa"(1), "aaa"(1), "a"(1), "aa"(1), "a"(1). Sum = 6

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters.

Visualization

Tap to expand
Total Appeal of A String INPUT String s = "abbca" a i=0 b i=1 b i=2 c i=3 a i=4 All Substrings (15 total): a, b, b, c, a ab, bb, bc, ca abb, bbc, bca abbc, bbca abbca Appeal = distinct chars count "abbca" has appeal = 3 (a, b, c are distinct) Track last[] array: last['a']=4, last['b']=2, last['c']=3 ALGORITHM STEPS 1 Initialize Tracking last[c] = -1 for all chars total = 0, contribution = 0 2 Iterate Each Position For i from 0 to n-1: char c = s[i] 3 Update Contribution contribution += i - last[c] (new substrings with c) 4 Accumulate Total total += contribution last[c] = i (update) Iteration Table i=0 'a': cont=1, total=1 i=1 'b': cont=3, total=4 i=2 'b': cont=4, total=8 i=3 'c': cont=8, total=16 i=4 'a': cont=12, total=28 FINAL RESULT Total Appeal 28 OK Appeal Breakdown: Length 1: 5 subs, appeal=5 Length 2: 4 subs, appeal=7 Length 3: 3 subs, appeal=6 Length 4: 2 subs, appeal=6 Length 5: 1 sub, appeal=3 Sum: 5+7+6+6+3+1 = 28 Time: O(n) Space: O(26) = O(1) Optimized approach avoids counting each substring Key Insight: Instead of counting appeal for each substring (O(n^2)), track last occurrence of each character. At position i, character c contributes to (i - last[c]) new substrings ending at i. The running contribution at each position gives total appeal when accumulated. Set reuse optimizes memory. TutorialsPoint - Total Appeal of A String | Optimized with Set Reuse
Asked in
Google 15 Facebook 12 Amazon 8
25.6K Views
Medium Frequency
~25 min Avg. Time
852 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen