Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Let's define a function countUniqueChars(s) that returns the number of unique characters in s.
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 <= 105s consists of uppercase English letters only.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Dynamic Programming
"ABC"
"ABA"
"LEETCODE"
total-appeal-of-a-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #828: Count Unique Characters of All Substrings of a Given String
class Solution {
public int uniqueLetterString(String s) {
List<Integer>[] d = new List[26];
Arrays.setAll(d, k -> new ArrayList<>());
for (int i = 0; i < 26; ++i) {
d[i].add(-1);
}
for (int i = 0; i < s.length(); ++i) {
d[s.charAt(i) - 'A'].add(i);
}
int ans = 0;
for (var v : d) {
v.add(s.length());
for (int i = 1; i < v.size() - 1; ++i) {
ans += (v.get(i) - v.get(i - 1)) * (v.get(i + 1) - v.get(i));
}
}
return ans;
}
}
// Accepted solution for LeetCode #828: Count Unique Characters of All Substrings of a Given String
func uniqueLetterString(s string) (ans int) {
d := make([][]int, 26)
for i := range d {
d[i] = []int{-1}
}
for i, c := range s {
d[c-'A'] = append(d[c-'A'], i)
}
for _, v := range d {
v = append(v, len(s))
for i := 1; i < len(v)-1; i++ {
ans += (v[i] - v[i-1]) * (v[i+1] - v[i])
}
}
return
}
# Accepted solution for LeetCode #828: Count Unique Characters of All Substrings of a Given String
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
// Accepted solution for LeetCode #828: Count Unique Characters of All Substrings of a Given String
impl Solution {
pub fn unique_letter_string(s: String) -> i32 {
let mut d: Vec<Vec<i32>> = vec![vec![-1; 1]; 26];
for (i, c) in s.chars().enumerate() {
d[(c as usize) - ('A' as usize)].push(i as i32);
}
let mut ans = 0;
for v in d.iter_mut() {
v.push(s.len() as i32);
for i in 1..v.len() - 1 {
ans += (v[i] - v[i - 1]) * (v[i + 1] - v[i]);
}
}
ans as i32
}
}
// Accepted solution for LeetCode #828: Count Unique Characters of All Substrings of a Given String
function uniqueLetterString(s: string): number {
const d: number[][] = Array.from({ length: 26 }, () => [-1]);
for (let i = 0; i < s.length; ++i) {
d[s.charCodeAt(i) - 'A'.charCodeAt(0)].push(i);
}
let ans = 0;
for (const v of d) {
v.push(s.length);
for (let i = 1; i < v.length - 1; ++i) {
ans += (v[i] - v[i - 1]) * (v[i + 1] - v[i]);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.