Count the Number of Special Characters I (LeetCode 3120): Solution and Explanation

Easy
Hash Table
String

A letter is special when it shows up in lowercase and in uppercase somewhere in the word. Read the word once, switching on a lowercase flag or an uppercase flag for each letter, then count the letters whose two flags are both on. "aaAbcBC" has 3 special letters: a, b and c.

Intuition

Positions and counts do not matter here. All that matters for each of the 26 letters is whether its lowercase form occurs and whether its uppercase form occurs.

That is two yes or no answers per letter, which fit in two arrays of 26 booleans.

Once the word is read, a letter is special exactly when both of its switches are on.

Approach: Two flag arrays

  1. Create lower and upper, each 26 booleans set to false.
  2. For each character c: if it is lowercase, set lower[c - 'a']; otherwise set upper[c - 'A'].
  3. Sweep k from 0 to 25 and count the columns where lower[k] and upper[k] are both true.
  4. Return the count.

Step-by-step example

word = "aaAbcBC"
  1. a, a switch on lower[a]. A switches on upper[a].
  2. b and c switch on lower[b] and lower[c].
  3. B and C switch on upper[b] and upper[c].
  4. The sweep finds columns a, b and c with both switches on, so the answer is 3.

Code: Python, Java, C++

1class Solution:
2    def numberOfSpecialChars(self, word: str) -> int:
3        lower = [False] * 26
4        upper = [False] * 26
5        for c in word:
6            if c.islower():
7                lower[ord(c) - ord('a')] = True
8            else:
9                upper[ord(c) - ord('A')] = True
10        count = 0
11        for k in range(26):
12            if lower[k] and upper[k]:
13                count += 1
14        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the word plus a fixed sweep of 26 columns.

Space

O(1)

Two arrays of 26 flags, independent of the word length.

Other approaches

Set intersection (time O(n), space O(1))

Build the set of lowercase letters and the set of uppercase letters converted to lowercase, then return the size of their intersection. Short in Python, same idea.

Two bit masks (time O(n), space O(1))

Keep two 26-bit integers, set bit c - 'a' or c - 'A', and return the popcount of lowerMask & upperMask.

Common mistakes

  • Counting a letter once per occurrence instead of once per letter. "aAaA" has 1 special letter, not 2.
  • Requiring the lowercase form to come before the uppercase form. That ordering rule belongs to Part II, not this problem.
  • Mixing up the offsets: lowercase letters index from 'a', uppercase from 'A'.

Frequently asked questions

Does the order of the two cases matter?

No. In this version a letter is special as soon as both forms occur anywhere, in any order.

Why sweep 26 columns at the end instead of counting during the scan?

Counting during the scan also works if you count only the moment a column becomes complete. The final sweep is simpler and cannot double count.

What is the largest possible answer?

26, when every letter occurs in both cases. That needs at least 52 characters, so with the limit of 50 the answer here is at most 25.