Skip to main content
Back to problems
#3121
Medium Algorithms

Count the number of special characters ii

Hash Table String
43.3% acceptance
Feb 23, 2026
181
16
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn number_of_special_chars(word: String) -> i32 {
    // For each letter: last index of lowercase, first index of uppercase
    let mut last_lower = [usize::MAX; 26];
    let mut first_upper = [usize::MAX; 26];
    for (idx, b) in word.bytes().enumerate() {
      if b.is_ascii_lowercase() {
        last_lower[(b - b'a') as usize] = idx;
      } else if first_upper[(b - b'A') as usize] == usize::MAX {
        first_upper[(b - b'A') as usize] = idx;
      }
    }
    (0..26)
      .filter(|&i| last_lower[i] != usize::MAX && first_upper[i] != usize::MAX && last_lower[i] < first_upper[i])
      .count() as i32
  }
}