#3121
Count the Number of Special Characters II
MediumHash TableStringHash MapSet
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a single pass through the string to track the first occurrences of uppercase and lowercase letters. This reduces the need for nested loops and searches, making it efficient.
⚙️
Algorithm
6 steps- 1Step 1: Create two sets to track lowercase and uppercase characters.
- 2Step 2: Create a map to track the first occurrence of each character's uppercase and lowercase versions.
- 3Step 3: Iterate through the string and populate the sets and map.
- 4Step 4: For each character, check if it is in both sets and if the lowercase occurs before the uppercase in the map.
- 5Step 5: Count valid special characters based on the conditions.
- 6Step 6: Return the count of special characters.
solution.py25 lines
1# Full working Python code
2
3def countSpecialCharacters(word):
4 lower_seen = set()
5 upper_seen = set()
6 position = {}
7 special_count = 0
8
9 for i, c in enumerate(word):
10 if c.islower():
11 lower_seen.add(c)
12 position[c] = (i, 'lower')
13 else:
14 upper_seen.add(c)
15 position[c.lower()] = (i, 'upper')
16
17 for c in lower_seen:
18 if c.upper() in upper_seen:
19 if position[c][0] < position[c.upper()][0]:
20 special_count += 1
21
22 return special_count
23
24# Example usage
25print(countSpecialCharacters('aaAbcBC')) # Output: 3ℹ
Complexity note: This complexity is linear because we only make a single pass through the string and use additional space for sets and maps to track occurrences.
- 1Special characters must have both lowercase and uppercase forms present.
- 2The order of occurrences is crucial: lowercase must appear before uppercase.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.