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

Greatest English Letter in Upper and Lower Case

Number: 1363

Difficulty: Easy

Paid? No

Companies: Microsoft


Problem Description

Given a string of English letters, return the greatest English letter (in uppercase) that appears in both uppercase and lowercase form in the string. If no such letter exists, return an empty string.


Key Insights

  • Use two sets (or equivalent) to record the occurrence of uppercase and lowercase letters found in the string.
  • Iterate over the characters to fill the corresponding sets.
  • Then check from 'Z' down to 'A' to determine the highest letter that appears in both sets.
  • Since the English alphabet is fixed, iterating over letters is constant time.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1) (or constant space) since the maximum number of stored elements is limited to 26 letters for each case.


Solution

We first traverse the input string once to populate two sets: one for lowercase letters and one for uppercase letters. After that, we iterate from 'Z' down to 'A' and check whether each letter's lowercase variant (using a conversion) is present in the lowercase set. The first letter found that meets this condition is the answer because we are iterating from the greatest letter (by alphabetical order) downward. If no letter is found that exists in both sets, we return an empty string.


Code Solutions

# Function to find the greatest English letter present in both cases
def greatest_letter(s: str) -> str:
    # Set to keep track of lowercase letters in the string
    lower_set = set()
    # Set to keep track of uppercase letters in the string
    upper_set = set()
    
    # Iterate over every character in the string
    for ch in s:
        # Add character to appropriate set based on its case
        if ch.islower():
            lower_set.add(ch)
        else:
            upper_set.add(ch)
    
    # Iterate from 'Z' to 'A' to get the greatest letter
    for char in range(ord('Z'), ord('A') - 1, -1):
        # If the uppercase letter exists and its lowercase version is also present
        if chr(char) in upper_set and chr(char).lower() in lower_set:
            return chr(char)
    
    # If no letter meets the criteria, return an empty string
    return ""

# Example usage:
print(greatest_letter("lEeTcOdE"))  # Expected output: "E"
← Back to All Questions