Count the Number of Special Characters II Problem
#3121
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 3121.
You are given a string word. A letter c is called special if it appears both in lowercase and uppercase in word, and every lowercase occurrence of c appears before the first uppercase occurrence of c.
Return the number of special letters in word.
Example 1:
Input: word = "aaAbcBC"
Output: 3
Explanation:
The special characters are 'a', 'b', and 'c'.
Example 2:
Input: word = "abc"
Output: 0
Explanation:
There are no special characters in word.
Example 3:
Input: word = "AbBCab"
Output: 0
Explanation:
There are no special characters in word.
Constraints:
1 <= word.length <= 2 * 10^5wordconsists of only lowercase and uppercase English letters.
Solution
Approach: Hash Table or Array
Store, for every character, the position where it first appears (first) and where it last appears (last).
A letter is special when its lowercase form appears, its uppercase form appears, and the last lowercase occurrence comes before the first uppercase occurrence: last[lower] < first[upper]. Count such letters.
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:
first, last = {}, {}
for i, c in enumerate(word):
if c not in first:
first[c] = i
last[c] = i
return sum(
a in last and b in first and last[a] < first[b]
for a, b in zip(ascii_lowercase, ascii_uppercase)
)