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 INPUT word = "aaAbcBC" a 0 a 1 A 2 b 3 c 4 B 5 C 6 Lowercase Uppercase Special: lowercase before first uppercase Track: firstLower, firstUpper lastLower, hasUpper ALGORITHM STEPS 1 Initialize Trackers firstLower[], lastLower[] firstUpper[], hasUpper[] 2 Single Pass Scan For each char, record first/last positions 3 Check Each Letter Has both cases? lastLower < firstUpper? 4 Count Special Increment count if conditions met Validation Check: 'a': last(1) < first_A(2) OK 'b': last(3) < first_B(5) OK 'c': last(4) < first_C(6) OK FINAL RESULT Special Letters Found: a/A OK b/B OK c/C OK Output: 3 All 3 letters (a, b, c) appear in both cases with lowercase first! Time: O(n) | Space: O(1) Single pass, 26-letter arrays Key Insight: Track the LAST occurrence of lowercase and FIRST occurrence of uppercase for each letter. A letter is special only if: (1) both cases exist, AND (2) lastLower < firstUpper. This ensures ALL lowercase appearances come before ANY uppercase appearance. TutorialsPoint - Count the Number of Special Characters II | Single Pass Optimal
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