We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count the Number of Special Characters I

Number: 3408

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

You are given a string word. A letter is called special if it appears in both lowercase and uppercase in word. Return the number of special letters in word.


Key Insights

  • Use two sets: one for lowercase characters and one for uppercase characters.
  • A letter is special if its lowercase version exists in both sets.
  • The input size is small (maximum 50 characters), so a simple iteration over the string is efficient.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string word. Space Complexity: O(1) since we only store at most 26 lowercase and 26 uppercase characters.


Solution

We iterate through the string and add characters to two separate sets (one for lowercase and one for uppercase). Then, we iterate through one of the sets (preferably lowercase) and check if the corresponding uppercase version is present in the uppercase set. Each match indicates a special character. The count of these matches is returned as the result.


Code Solutions

# Define the function to count special characters.
def count_special_characters(word):
    # Create sets for lowercase and uppercase characters.
    lowercase_set = set()
    uppercase_set = set()
    
    # Iterate through each character in the word.
    for char in word:
        # If the character is lowercase, add it to lowercase_set.
        if char.islower():
            lowercase_set.add(char)
        # If the character is uppercase, add it to uppercase_set.
        elif char.isupper():
            uppercase_set.add(char)
    
    # Initialize the counter for special characters.
    special_count = 0
    # For each lowercase letter in the set, check if its uppercase version exists.
    for char in lowercase_set:
        if char.upper() in uppercase_set:
            special_count += 1
            
    # Return the count of special characters.
    return special_count

# Example usage:
print(count_special_characters("aaAbcBC"))  # Output: 3
← Back to All Questions