Count Unique Characters of All Substrings of a Given String - Problem
Let's define a function countUniqueChars(s) that returns the number of unique characters in s.
For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
Given a string s, return the sum of countUniqueChars(t) where t is a substring of s.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
Input & Output
Example 1 — Basic Case
$
Input:
s = "ABC"
›
Output:
10
💡 Note:
Substrings: "A"(1), "B"(1), "C"(1), "AB"(2), "BC"(2), "ABC"(3). Sum: 1+1+1+2+2+3 = 10
Example 2 — Repeated Characters
$
Input:
s = "ABA"
›
Output:
8
💡 Note:
Substrings: "A"(1), "B"(1), "A"(1), "AB"(2), "BA"(2), "ABA"(1). Sum: 1+1+1+2+2+1 = 8
Example 3 — Single Character
$
Input:
s = "A"
›
Output:
1
💡 Note:
Only one substring "A" with 1 unique character. Sum: 1
Constraints
- 1 ≤ s.length ≤ 104
- s consists of uppercase English letters only.
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Given string with characters at positions
2
Generate Substrings
All possible contiguous substrings
3
Count & Sum
Count unique chars in each substring and sum
Key Takeaway
🎯 Key Insight: Calculate each character's contribution to all substrings instead of checking every substring individually
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code