Description
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.
Solutions
This solution is nearly identical to the second approach but uses an Int8Array instead of a regular Array for better memory efficiency. Int8Array is a typed array that stores only 8-bit signed integers, consuming less memory than a standard JavaScript array. Like the array-based solution, it maintains 52 positions (26 letters × 2 cases), maps each character to its position via ASCII code, and increments the counter when a character's case is seen for the first time while its opposite case has already been encountered.
/**
* @param {string} word
* @return {number}
*/
var numberOfSpecialChars = function(word) {
const arr = new Int8Array(52);
let res = 0;
for (let i = 0; i < word.length; i++) {
const code = word.charCodeAt(i);
const pos = code - (code >= 97 ? 71 : 65);
if (arr[pos] === 0 && arr[(pos + 26) % 52] > 0) {
res++;
}
arr[pos]++;
}
return res;
};