Leetcode 3121: Count the Number of Special Characters II

grid47
grid47
Exploring patterns and algorithms
Dec 30, 2023 7 min read

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.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `word` of length n.
Example: word = "abcABca"
Constraints:
• 1 <= word.length <= 2 * 10^5
• word consists of only lowercase and uppercase English letters
Output: Return the number of special letters in the string `word`.
Example: Output: 2
Constraints:
Goal: Identify letters that appear in both lowercase and uppercase in the string and check if every lowercase occurrence precedes the first uppercase occurrence.
Steps:
• 1. Initialize a vector of size 26 to keep track of the occurrences of each letter in `word`.
• 2. Loop through the string and update the vector to mark the status of each character.
• 3. After processing the string, check which letters have both lowercase and uppercase occurrences where all lowercase letters precede the uppercase ones.
• 4. Count and return the total number of such special letters.
Goal: The problem constraints define the limits on the length and content of the string.
Steps:
• 1 <= word.length <= 2 * 10^5
• word consists of only lowercase and uppercase English letters
Assumptions:
• The input string will only contain lowercase and uppercase English letters.
• The string will have a length between 1 and 2 * 10^5 characters.
Input: word = "abcABca"
Explanation: The special characters are 'a' and 'b', because they appear in both lowercase and uppercase, and all lowercase occurrences precede the uppercase ones.

Input: word = "hello"
Explanation: No special characters exist in this string, as no letter appears in both uppercase and lowercase.

Input: word = "AaaBcAB"
Explanation: The letter 'a' appears both in lowercase and uppercase, but the lowercase 'a' occurs after the uppercase 'A', so it's not special.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus