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
Count Unique Characters of All Substrings INPUT String s = "ABC" A B C i=0 i=1 i=2 All Substrings: "A" - unique: 1 "B" - unique: 1 "C" - unique: 1 "AB" - unique: 2 "BC" - unique: 2 "ABC" - unique: 3 Total: 6 substrings Sum: 1+1+1+2+2+3=10 ALGORITHM STEPS 1 Contribution Idea Count each char's contribution to total 2 Find Boundaries For char at i: find prev[i] and next[i] 3 Calculate Contribution contrib[i] = (i-prev) * (next-i) 4 Sum All Total = sum of all contributions Contribution Table: A: (0-(-1))*(3-0)=1*3=3 B: (1-(-1))*(3-1)=2*2=4 C: (2-(-1))*(3-2)=3*1=3 FINAL RESULT Sum of Contributions: A 3 B 4 C 3 + + 3 + 4 + 3 Output: 10 OK Sum verified correctly! Key Insight: Instead of checking all substrings O(n^2), calculate each character's contribution. For character at position i, it contributes uniquely to (i - prev) * (next - i) substrings, where prev/next are positions of same character. This achieves O(n) time complexity! TutorialsPoint - Count Unique Characters of All Substrings of a Given String | Contribution-Based Approach
Asked in
Google 25 Amazon 18 Facebook 12
28.5K Views
Medium Frequency
~35 min Avg. Time
847 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