3120. Count the Number of Special Characters I
- Hash Set
- String
TIME
O(n)
SPACE
O(1)
Intuition
A letter is special only when its lowercase form and uppercase form both appear somewhere in the string.
So we can track lowercase letters in one set and uppercase letters converted to lowercase in another set. The special letters are exactly the letters present in both sets.
Approach
- Create an empty set for lowercase letters.
- Create an empty set for uppercase letters, stored as lowercase.
- Scan every character in
word:- if it is lowercase, add it to the lowercase set
- otherwise, convert it to lowercase and add it to the uppercase set
- Return the size of the intersection of the two sets.
Complexity
- Time: O(n), scan the string once
- Space: O(1), at most 26 lowercase and 26 uppercase letters are stored
Edge Cases
- All lowercase letters -> answer is
0 - All uppercase letters -> answer is
0 - Repeated letters -> sets count each letter once
- Mixed case for the same letter -> counted once
Code
class Solution:
def numberOfSpecialChars(self, word: str) -> int:
"""
3120. Count the Number of Special Characters I
Time: O(n)
Space: O(1)
"""
lowercase = set()
uppercase = set()
for char in word:
if char.islower():
lowercase.add(char)
else:
uppercase.add(char.lower())
return len(lowercase & uppercase)import java.util.HashSet;
import java.util.Set;
/**
* 3120. Count the Number of Special Characters I
* Time: O(n)
* Space: O(1)
*/
class Solution {
public int numberOfSpecialChars(String word) {
Set<Character> lowercase = new HashSet<>();
Set<Character> uppercase = new HashSet<>();
for (int index = 0; index < word.length(); index++) {
char current = word.charAt(index);
if (Character.isLowerCase(current)) {
lowercase.add(current);
} else {
uppercase.add(Character.toLowerCase(current));
}
}
int answer = 0;
for (char letter : lowercase) {
if (uppercase.contains(letter)) {
answer++;
}
}
return answer;
}
}