Total Appeal of A String — LeetCode 2262 Python Solution

HardHash TableStringDynamic Programming
Problem
#2262
Reading time
2 min

The problem

The appeal of a string is the number of distinct characters found in the string. For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.

Example

Input
s = "abbca"
Output
28
Explanation
The following are the substrings of "abbca":

Python solution

Python
class Solution:
    def appealSum(self, s: str) -> int:
        ans = t = 0
        pos = [-1] * 26
        for i, c in enumerate(s):
            c = ord(c) - ord('a')
            t += i - pos[c]
            ans += t
            pos[c] = i
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(|\Sigma|), where n is the length of the string s, and |\Sigma| is the size of the character set auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2262. Total Appeal of A 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 2262. Total Appeal of A String?
LeetCode 2262. Total Appeal of A String is rated Hard on LeetCode.
What is the time complexity of LeetCode 2262. Total Appeal of A String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2262. Total Appeal of A String?
The Python solution on this page uses O(|\Sigma|), where n is the length of the string s, and |\Sigma| is the size of the character set auxiliary space.
What topics does LeetCode 2262. Total Appeal of A String cover?
LeetCode 2262. Total Appeal of A 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