Skip to content
Problem 828 · LeetCode 828(opens in a new tab)

Count Unique Characters of All Substrings of a Given String

HardDynamic programming

For a string t, call a letter unique in t if it occurs exactly once in t. For example, in "PAPER" the unique letters are A, E and R, so its score is 3.

Given a string s of upper-case letters, add up the scores of all its substrings. Substrings at different positions are counted separately, even when they spell the same text. The answer fits in a 32-bit signed integer.

Example 1

Input:  s = "ABCB"
Output: 16
Why:    only "BCB" and "ABCB" lose points, to the repeated B
2 more examples and the constraints

Example 2

Input:  s = "ZZ"
Output: 2
Why:    "Z" scores 1 twice; "ZZ" scores 0

Example 3

Input:  s = "QRST"
Output: 20
Why:    no repeats, so each substring scores its length

Constraints

  • 1 ≤ length of s ≤ 100,000
  • s holds upper-case English letters only

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Grow every substringO(n²)
  2. Count each letter's contributionO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 lettersVerdict
Grow every substringO(n²)
5 billion steps; too slow
Count each letter's contributionO(n)
Best; one pass

n = length of s.

Edge cases to test

  • One letter. "K" has one substring scoring 1.
  • All the same letter. "ZZ": only the single-letter substrings score; each copy is boxed in by its neighbours.
  • All different letters. Every substring scores its length; the total is the sum of all substring lengths.
  • Letter seen only once. Its contribution is (p + 1) × (n − p), using −1 and n as the boundaries.
  • Big products. Each term multiplies two gaps of up to 100,000; summing in 64-bit math in Java and C++ is a cheap safety margin.

Common mistakes

  • Counting distinct letters instead of letters that occur exactly once.
  • Forgetting the final pass, so the last copy of every letter scores nothing.
  • Using 0 and n − 1 as the default boundaries instead of −1 and n, which undercounts by one choice on each side.

How to talk through it

  1. 1Clarify. Unique means exactly once in the substring? Do repeated substrings count each time?
  2. 2Give the brute force. Grow each substring with counters; O(n²) is 5 billion steps at the limit.
  3. 3Flip the sum. Count, for each position, how many substrings it is the only copy of its letter in.
  4. 4Find the boundaries. That count is (gap to previous same letter) × (gap to next same letter); track the last two positions.
  5. 5Test out loud. Run "ZZ", "QRST" and "ABCB" by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?