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.

Input & Output

Example 1 — Mixed Valid Cases
$ Input: word = "aaAbcBC"
Output: 3
💡 Note: Special characters are 'a', 'b', and 'c'. Letter 'a': lowercase at positions 0,1 before uppercase at 2. Letter 'b': lowercase at 3 before uppercase at 5. Letter 'c': lowercase at 4 before uppercase at 6.
Example 2 — Invalid Order
$ Input: word = "abc"
Output: 0
💡 Note: No uppercase letters exist, so no letter can be special (needs both cases).
Example 3 — Constraint Violation
$ Input: word = "AbBcC"
Output: 0
💡 Note: All letters appear in uppercase before lowercase, violating the ordering constraint.

Constraints

  • 1 ≤ word.length ≤ 1000
  • word consists of only lowercase and uppercase English letters.

Visualization

Tap to expand
Count Special Characters II: "aaAbcBC"aaAbcBCpos 0pos 1pos 2pos 3pos 4pos 5pos 6Analysis:• Letter 'a': lowercase(0,1) → uppercase(2) ✓• Letter 'b': lowercase(3) → uppercase(5) ✓• Letter 'c': lowercase(4) → uppercase(6) ✓Result: 3 Special Characters
Understanding the Visualization
1
Input
String with mixed case letters: "aaAbcBC"
2
Process
Check each letter for both cases and proper ordering
3
Output
Count of valid special characters: 3
Key Takeaway
🎯 Key Insight: Track when lowercase appears after uppercase to identify invalid special characters
Asked in
Google 45 Amazon 32 Microsoft 28
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen