← Back to list

3121. Count the Number of Special Characters II

🧩 Problem:

Sara | Software Developer & Tech Writer · 2026-05-27 04:47 · 20 claps · 0.8 min read
#java #coding #leetcode #problem-solving #3121
Open on Medium ↗
Wiki topics: 💻 · Programming

3121. Count the Number of Special Characters II

🧩 Problem:

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.

Constraints:

  • 1 <= word.length <= 2 * 105
  • word consists of only lowercase and uppercase English letters.

🔑 Key Idea:

👉 Store last lowercase index and first uppercase index; a letter is special if lowercase appears before uppercase.

Solution:

class Solution {

public int numberOfSpecialChars(String word) {

int[] lower = new int[26];

int[] upper = new int[26];

Arrays.fill(lower, -1);

Arrays.fill(upper, -1);

for (int i = 0; i < word.length(); i++) {

char ch = word.charAt(i);

if (ch >= ‘a’ && ch <= ‘z’) {

// Track the last occurrence of each lowercase letter

lower[ch — ‘a’] = i;

} else {

// Track the first occurrence of each uppercase letter

if (upper[ch — ‘A’] == -1)

upper[ch — ‘A’] = i;

}

}

int count = 0;

for (int i = 0; i < 26; i++) {

if (lower[i] != -1 && upper[i] != -1 && lower[i] < upper[i])

count++;

}

return count;

}

}


메타데이터
post_id
8effe0728007
slug
3121-count-the-number-of-special-characters-ii-8effe0728007
url
https://medium.com/@sarawrites/3121-count-the-number-of-special-characters-ii-8effe0728007
canonical_url
https://medium.com/@sarawrites/3121-count-the-number-of-special-characters-ii-8effe0728007
author_url
https://medium.com/@sarawrites
status
ok
fetched_at
2026-06-09 15:37:30