Count Unique Characters of All Substrings of a Given String — LeetCode 828 Python Solution

HardHash TableStringDynamic Programming
Problem
#828
Reading time
2 min

The 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.

Example

Input
s = "ABC"
Output
10
Explanation
All possible substrings are: "A","B","C","AB","BC" and "ABC".

Python solution

Python
class Solution:
    def uniqueLetterString(self, s: str) -> int:
        d = defaultdict(list)
        for i, c in enumerate(s):
            d[c].append(i)
        ans = 0
        for v in d.values():
            v = [-1] + v + [len(s)]
            for i in range(1, len(v) - 1):
                ans += (v[i] - v[i - 1]) * (v[i + 1] - v[i])
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 828. Count Unique Characters of All Substrings of a Given String is filed here because LeetCode tags it Dynamic Programming, which is the vocabulary this hub collects.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 828. Count Unique Characters of All Substrings of a Given String?
LeetCode 828. Count Unique Characters of All Substrings of a Given String is rated Hard on LeetCode.
What is the time complexity of LeetCode 828. Count Unique Characters of All Substrings of a Given String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 828. Count Unique Characters of All Substrings of a Given String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 828. Count Unique Characters of All Substrings of a Given String cover?
LeetCode 828. Count Unique Characters of All Substrings of a Given String is tagged Hash Table, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview