Count the Number of Special Characters I Problem
#3120
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3120.
You are given a string word. A letter is called special if it appears both in lowercase and uppercase in word.
Return the number of special letters in word.
Example 1:
Input: word = "aaAbcBC"
Output: 3
Explanation:
The special characters in word are 'a', 'b', and 'c'.
Example 2:
Input: word = "abc"
Output: 0
Explanation:
No character in word appears in uppercase.
Example 3:
Input: word = "abBCab"
Output: 1
Explanation:
The only special character in word is 'b'.
Constraints:
1 <= word.length <= 50wordconsists of only lowercase and uppercase English letters.
Solution
Approach: Hash Set or Array
Record which characters occur in word. Then for each of the 26 letters, count it if both its lowercase and uppercase forms occur.
Complexity: O(n + |S|) time and O(|S|) space, where |S| is the character set size (at most 128).
from string import ascii_lowercase, ascii_uppercase
class Solution:
def numberOfSpecialChars(self, word: str) -> int:
s = set(word)
return sum(a in s and b in s for a, b in zip(ascii_lowercase, ascii_uppercase))