Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count the Number of Special Characters I

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3120" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given a string word. A letter is called special if it appears both in lowercase and uppercase in word. Return the number of special letters in word. Example 1: Input: word = "aaAbcBC" Output: 3 Explanation: The special characters in word are 'a', 'b', and 'c'. Example 2: Input: word = "abc" Output: 0 Explanation: No character in word appears in uppercase. Example 3: Input: word = "abBCab" Output: 1 Explanation: The only special character in word is 'b'. Constraints: 1 <= word.length <= 50 word consists of only lowercase and uppercase English letters.

Explanation

Here's the breakdown of the solution:

  • Use Sets for Efficient Lookup: Utilize sets to store lowercase and uppercase letters encountered in the string. Sets provide O(1) average time complexity for checking the presence of an element.
  • Identify Special Letters: Iterate through the lowercase set and check if the corresponding uppercase letter exists in the uppercase set. If it does, increment the count of special letters.

  • Runtime & Storage Complexity: O(n) runtime, O(1) storage (since the size of the sets is bounded by the alphabet size which is constant).

Code

    def count_special_letters(word: str) -> int:
    """
    Given a string word. A letter is called special if it appears both in lowercase and uppercase in word.
    Return the number of special letters in word.

    Example 1:
    Input: word = "aaAbcBC"
    Output: 3
    Explanation: The special characters in word are 'a', 'b', and 'c'.

    Example 2:
    Input: word = "abc"
    Output: 0
    Explanation: No character in word appears in uppercase.

    Example 3:
    Input: word = "abBCab"
    Output: 1
    Explanation: The only special character in word is 'b'.

    Constraints:
    1 <= word.length <= 50
    word consists of only lowercase and uppercase English letters.
    """

    lowercase_letters = set()
    uppercase_letters = set()

    for char in word:
        if 'a' <= char <= 'z':
            lowercase_letters.add(char)
        else:
            uppercase_letters.add(char)

    count = 0
    for char in lowercase_letters:
        if char.upper() in uppercase_letters:
            count += 1

    return count

More from this blog

C

Chatmagic blog

2894 posts