855. Count Unique Characters of All Substrings of a Given String
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the sum of unique character counts over all substrings of a given string s. A direct approach of generating all substrings and counting unique characters for each would be too slow, likely O(n^3) or O(n^2), given n can be up to 10^5.
Solution
Count Unique Characters of All Substrings of a Given String in Python
import collections
class Solution:
def uniqueLetterString(self, s: str) -> int:
# index_map stores indices for each character.
# defaultdict(list) is convenient for this.
index_map = collections.defaultdict(list)
for i, char in enumerate(s):
index_map[char].append(i)
total_sum = 0
n = len(s)
# Iterate through each character's list of occurrences.
for char in index_map:
indices = index_map[char]
# Pad with sentinels for easier calculation.
padded_indices = [-1] + indices + [n]
# For each actual occurrence, calculate its contribution.
for i in range(1, len(padded_indices) - 1):
prev_idx = padded_indices[i-1]
curr_idx = padded_indices[i]
next_idx = padded_indices[i+1]
# Contribution of s[curr_idx]:
# Number of ways to choose left boundary: (curr_idx - prev_idx)
# Number of ways to choose right boundary: (next_idx - curr_idx)
total_sum += (curr_idx - prev_idx) * (next_idx - curr_idx)
return total_sum
Count Unique Characters of All Substrings of a Given String in Java
class Solution {
public int uniqueLetterString(String s) {
// indexMap stores indices for each character 'A'-'Z'.
// Using an array of lists for a fixed alphabet.
List<Integer>[] indexMap = new ArrayList[26];
for (int i = 0; i < 26; i++) {
indexMap[i] = new ArrayList<>();
}
for (int i = 0; i < s.length(); i++) {
indexMap[s.charAt(i) - 'A'].add(i);
}
long totalSum = 0;
int n = s.length();
// Iterate through each character's list of occurrences.
for (int i = 0; i < 26; i++) {
int prevIdx = -1; // Sentinel for the left boundary.
for (int j = 0; j < indexMap[i].size(); j++) {
int currIdx = indexMap[i].get(j);
// The next occurrence is the next one in the list, or n if it's the last.
int nextIdx = (j + 1 < indexMap[i].size()) ? indexMap[i].get(j + 1) : n;
// Contribution of s[currIdx]:
// Number of ways to choose left boundary: (currIdx - prevIdx)
// Number of ways to choose right boundary: (nextIdx - currIdx)
totalSum += (long)(currIdx - prevIdx) * (long)(nextIdx - currIdx);
prevIdx = currIdx; // Update prevIdx for the next iteration.
}
}
return (int)totalSum;
}
}
Count Unique Characters of All Substrings of a Given String in C++
class Solution {
public:
int uniqueLetterString(string s) {
// indexMap stores indices for each character 'A'-'Z'.
// Using an array is slightly faster than a map for a fixed, small alphabet.
vector<int> indexMap[26];
for (int i = 0; i < s.length(); ++i) {
indexMap[s[i] - 'A'].push_back(i);
}
long long totalSum = 0;
int n = s.length();
// Iterate through each character's occurrences.
for (int i = 0; i < 26; ++i) {
int prevIdx = -1; // Sentinel for the left boundary.
// For each occurrence of a character, calculate its contribution.
for (int currIdx : indexMap[i]) {
// The next occurrence is not known yet within this loop structure for a specific currIdx,
// so we can't directly use (curr - prev) * (next - curr) on the first pass.
// Let's adjust the logic slightly.
}
}
// Corrected logic: Iterate through indices and calculate contribution for each.
for (int i = 0; i < 26; ++i) {
int prevIdx = -1;
for (int j = 0; j < indexMap[i].size(); ++j) {
int currIdx = indexMap[i][j];
// The next occurrence is the next one in the list, or n if it's the last.
int nextIdx = (j + 1 < indexMap[i].size()) ? indexMap[i][j + 1] : n;
// Contribution of s[currIdx]:
// Number of ways to choose left boundary: (currIdx - prevIdx)
// Number of ways to choose right boundary: (nextIdx - currIdx)
totalSum += (long long)(currIdx - prevIdx) * (nextIdx - currIdx);
prevIdx = currIdx; // Update prevIdx for the next iteration.
}
}
return (int)totalSum;
}
};
Count Unique Characters of All Substrings of a Given String in TypeScript
function uniqueLetterString(s: string): number {
// indexMap stores indices for each character.
const indexMap: Map<string, number[]> = new Map();
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (!indexMap.has(char)) {
indexMap.set(char, []);
}
indexMap.get(char)!.push(i);
}
let totalSum = 0;
const n = s.length;
// Iterate through each character's list of occurrences.
for (const indices of indexMap.values()) {
// Pad with sentinels for easier calculation.
const paddedIndices = [-1, ...indices, n];
// For each actual occurrence, calculate its contribution.
for (let i = 1; i < paddedIndices.length - 1; i++) {
const prevIdx = paddedIndices[i - 1];
const currIdx = paddedIndices[i];
const nextIdx = paddedIndices[i + 1];
// Contribution of s[curr_idx]:
// Number of ways to choose left boundary: (currIdx - prevIdx)
// Number of ways to choose right boundary: (nextIdx - currIdx)
totalSum += (currIdx - prevIdx) * (nextIdx - currIdx);
}
}
return totalSum;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.