Count the Number of Special Characters II - Problem
You are given a string word. Your task is to find special characters that follow a very specific pattern.
A letter c is considered special if it meets both of these conditions:
- It appears in both lowercase and uppercase forms in the string
- Every lowercase occurrence of
cappears before the first uppercase occurrence ofc
For example, in the string "aaAbcBC":
- Letter
'a'is special: lowercase 'a' appears at indices 0,1 and uppercase 'A' appears at index 2 ✅ - Letter
'b'is NOT special: uppercase 'B' appears at index 4, but lowercase 'b' appears at index 5 (after the uppercase) ❌ - Letter
'c'is special: lowercase 'c' appears at index 6 and uppercase 'C' appears at index 7 ✅
Return the count of such special letters.
Input & Output
example_1.py — Basic case with mixed ordering
$
Input:
word = "aaAbcBC"
›
Output:
2
💡 Note:
Letters 'a' and 'c' are special. For 'a': lowercase at positions 0,1 come before uppercase at position 2. For 'c': lowercase at position 4 comes before uppercase at position 6. Letter 'b' is not special because lowercase 'b' at position 3 comes after uppercase 'B' at position 5.
example_2.py — All lowercase before uppercase
$
Input:
word = "abc"
›
Output:
0
💡 Note:
No special characters because there are no uppercase letters in the string. For a character to be special, it must appear in both lowercase and uppercase forms.
example_3.py — Perfect special characters
$
Input:
word = "abcdefABCDEF"
›
Output:
6
💡 Note:
All letters a-f are special because all lowercase letters appear first (positions 0-5) followed by all uppercase letters (positions 6-11). This satisfies the ordering condition for all 6 letters.
Constraints
- 1 ≤ word.length ≤ 104
- word consists of only English letters (both lowercase and uppercase)
- Follow-up: Can you solve this in O(n) time and O(1) extra space?
Visualization
Tap to expand
Understanding the Visualization
1
Scan the String
Track positions of each character as we encounter them
2
Update Positions
Maintain last lowercase and first uppercase positions for each letter
3
Validate Ordering
Check if all lowercase positions come before first uppercase position
4
Count Special Letters
Sum up letters that satisfy both existence and ordering conditions
Key Takeaway
🎯 Key Insight: We only need to track the last lowercase position and first uppercase position for each letter. If last_lowercase < first_uppercase, the letter is special!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code