Problem Description
Given a string word, a letter c is called special if it appears in both lowercase and uppercase in word, and every lowercase occurrence of c appears before the first uppercase occurrence of c. The task is to count the number of special letters in word.
Key Insights
- A letter is only special if it appears in both lowercase and uppercase forms.
- The order is crucial: All occurrences of the lowercase letter must occur before its first uppercase occurrence.
- By tracking the first appearance of an uppercase letter and the last appearance of the lowercase letter for each character, we can determine if the condition is satisfied.
- Since there are only 26 letters, iterating through each letter and checking conditions keeps the solution efficient.
Space and Time Complexity
Time Complexity: O(n) – we traverse the string once, and then iterate over 26 letters. Space Complexity: O(1) – we store only a constant amount of information for each letter.
Solution
We solve the problem by iterating through the string and tracking for each letter:
- The index of the first uppercase occurrence.
- The index of the last lowercase occurrence. For each letter from 'a' to 'z', if both forms exist and the last lowercase index is less than the first uppercase index, then the letter is special. This approach uses simple arrays (or dictionaries) for tracking indices and checks a single condition per letter.