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
Character Contribution MethodExample: s = "ABCA"Step 1: Character PositionsA: positions [0, 3]B: positions [1] C: positions [2]Step 2: Calculate ContributionsAโ‚€left=-1, right=3 โ†’ (0-(-1))ร—(3-0) = 3Bโ‚left=-1, right=4 โ†’ (1-(-1))ร—(4-1) = 6Cโ‚‚left=-1, right=4 โ†’ (2-(-1))ร—(4-2) = 6Aโ‚ƒleft=0, right=4 โ†’ (3-0)ร—(4-3) = 3Result: 3 + 6 + 6 + 3 = 18
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.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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