Skip to main content

Count Unique Characters of All Substrings of a Given String - Video Solutions

HardHash TableStringDynamic Programming

Count Unique Characters of All Substrings of a Given String | Leetcode 828

Techdose
22:0819,247 views
10 video solutions available

Count Unique Characters of All Substrings of a Given String - Video Solution

Watch 10 video solutions for Count Unique Characters of All Substrings of a Given String, a hard level problem involving Hash Table, String, Dynamic Programming. This walkthrough by Techdose has 19,247 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.

Problem Statement

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. The test cases are generated such that the answer fits in a 32-bit integer.

Notice that some substrings can be repeated so in this case you have to count the repeated ones too.

 

Example 1:

Input: s = "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10

Example 2:

Input: s = "ABA"
Output: 8
Explanation: The same as example 1, except countUniqueChars("ABA") = 1.

Example 3:

Input: s = "LEETCODE"
Output: 92

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of uppercase English letters only.
Read full problem with examples

Approach Overview

Problem Overview: Given a string s, compute the sum of counts of unique characters for every possible substring. A character contributes to a substring only if it appears exactly once in that substring. The challenge is avoiding the naive enumeration of all substrings while correctly counting each character’s contribution.

Approach 1: Brute Force Enumeration (O(n^3) time, O(1) space)

Generate every substring using two nested loops and compute the number of unique characters in each substring. For each substring, iterate again to count frequencies and check which characters appear exactly once. This approach directly follows the problem definition but performs redundant work because many substrings share overlapping segments. It works for small inputs but quickly becomes impractical as n grows.

Approach 2: Optimized Contribution Technique (O(n) time, O(1) space)

Instead of evaluating substrings individually, calculate how many substrings each character contributes to as a unique character. Track the previous two occurrences of each character. If a character appears at index i, its contribution equals (i - prev) * (next - i), where prev and next represent the nearest identical characters on each side. This counts all substrings where the character is the only occurrence. Iterating through the string once accumulates the total contribution efficiently.

Approach 3: Hash Map for Fast Lookups (O(n) time, O(k) space)

Maintain a hash map that stores the last two positions for each character. While iterating through the string, update contributions based on these positions. Hash lookups make it easy to support larger alphabets beyond uppercase letters. This technique relies on the same contribution principle but uses a dynamic structure rather than fixed arrays. It combines ideas from hash tables and string processing.

Approach 4: Divide and Conquer via Binary Search (O(n log n) time, O(n) space)

Store all indices of each character in sorted lists. For every position, binary search the previous and next occurrences of that character to compute its contribution range. The substring contribution formula remains the same, but binary search replaces direct index tracking. This approach is useful when preprocessing character positions or when extending the logic to multiple queries on the same string.

Recommended for interviews: The contribution-based O(n) solution is the expected answer. It shows you understand how substring ranges work and how to convert a brute force counting problem into a per-character contribution problem. Explaining the brute force first demonstrates baseline reasoning, while the optimized approach highlights strong knowledge of dynamic programming-style state tracking and index arithmetic.

Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(n^3)O(1)Conceptual baseline or very small strings
Optimized Contribution TechniqueO(n)O(1)Best general solution for interviews and large inputs
Hash Map for Fast LookupsO(n)O(k)When alphabet size varies or characters extend beyond fixed arrays
Divide and Conquer with Binary SearchO(n log n)O(n)Useful when character positions are pre-indexed or reused across queries