Count Unique Characters of All Substrings of a Given String - Problem
Given a string s, we need to find the sum of unique characters across all possible substrings of s.
Let's define countUniqueChars(t) as a function that returns the number of characters that appear exactly once in string t.
For example, if s = "LEETCODE":
- Characters 'L', 'T', 'C', 'O', 'D' appear exactly once โ
countUniqueChars("LEETCODE") = 5 - Characters 'E' appears twice, so it's not counted
Your task is to return the sum of countUniqueChars(t) for every substring t of s.
Important: Some substrings may be identical, but each occurrence must be counted separately.
Example: For s = "ABC", we consider substrings: "A", "B", "C", "AB", "BC", "ABC" - and count unique characters in each.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "ABC"
โบ
Output:
10
๐ก Note:
Substrings: "A"(1) + "B"(1) + "C"(1) + "AB"(2) + "BC"(2) + "ABC"(3) = 10 unique characters total
example_2.py โ Repeated Characters
$
Input:
s = "ABA"
โบ
Output:
8
๐ก Note:
Substrings: "A"(1) + "B"(1) + "A"(1) + "AB"(2) + "BA"(2) + "ABA"(1, only B is unique) = 8
example_3.py โ Single Character
$
Input:
s = "A"
โบ
Output:
1
๐ก Note:
Only one substring "A" with 1 unique character
Constraints
- 1 โค s.length โค 104
- s consists of uppercase English letters only
- Answer fits in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Index Grouping
Group all positions where each character appears
2
Boundary Calculation
For each position, find the nearest same characters before and after
3
Contribution Formula
Calculate contribution as (left_distance) ร (right_distance)
4
Sum All Contributions
Add up contributions from all character positions
Key Takeaway
๐ฏ Key Insight: Instead of checking every substring, calculate each character's total contribution across all substrings where it appears exactly once using mathematical boundaries.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code