#3120
Count the Number of Special Characters I
EasyHash TableStringHash 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 uses a single pass to count occurrences of each character, allowing us to determine if a character is special in a more efficient manner. This reduces the number of checks needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency array of size 52 to count occurrences of each letter (26 lowercase + 26 uppercase).
- 2Step 2: Traverse the word and update the frequency array based on the character's case.
- 3Step 3: Count how many characters have both lowercase and uppercase occurrences.
solution.py8 lines
1# Full working Python code
2word = 'aaAbcBC'
3frequency = [0] * 52
4for char in word:
5 index = ord(char) - ord('A') if char.isupper() else ord(char) - ord('a') + 26
6 frequency[index] += 1
7special_count = sum(1 for i in range(26) if frequency[i] > 0 and frequency[i + 26] > 0)
8print(special_count)ℹ
Complexity note: The time complexity is O(n) because we traverse the string once to count characters and then check the frequency array, which has a constant size of 52.
- 1Characters can be represented using their ASCII values for efficient indexing.
- 2Using a frequency array allows for quick checks of character presence.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.