#828
Count Unique Characters of All Substrings of a Given String
HardHash TableStringDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages the idea of tracking the last occurrence of each character to efficiently calculate the contribution of each character to the unique character count in substrings. This avoids the need to generate all substrings explicitly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a last occurrence array to store the last index of each character.
- 2Step 2: Iterate through the string, maintaining a count of unique characters contributed by each character.
- 3Step 3: For each character, calculate its contribution based on its last occurrence and update the total count.
solution.py12 lines
1# Full working Python code
2
3def countUniqueChars(s):
4 last_occurrence = [-1] * 26
5 total_count = 0
6 n = len(s)
7 for i in range(n):
8 char_index = ord(s[i]) - ord('A')
9 last_index = last_occurrence[char_index]
10 total_count += (i - last_index) * (n - i)
11 last_occurrence[char_index] = i
12 return total_countℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string, and each character's contribution is calculated in constant time. The space complexity is O(1) since the size of the last occurrence array is fixed at 26 (for each uppercase letter).
- 1Each character's contribution to unique counts can be calculated based on its position and last occurrence.
- 2Understanding how to efficiently track character positions can significantly reduce computation time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.