Given a string s
of English letters, return the greatest English letter which occurs as both a lowercase and uppercase letter in s
. The returned letter should be in uppercase. If no such letter exists, return an empty string.
s = "lEeTcOdE"
"E"
s = "arRAzFif"
"R"
s = "AbCdEfGhIjK"
""
What is the length of the string?
The length of the string s
can vary but will be constrained by typical LeetCode input limits (usually up to (10^5)).
Is the string case-sensitive initially?
Yes, the string contains both uppercase and lowercase English letters and is case-sensitive initially.
What should be returned if there are multiple valid letters?
The greatest letter (lexicographically) occurring in both cases should be returned in uppercase.
Are there any constraints on the contents of the string?
The string s
consists only of English letters.
This approach ensures we check for the lexicographically greatest letter due to the reverse iteration through the alphabet.
def greatestLetter(s: str) -> str:
seen = set(s)
for char in range(ord('Z'), ord('A') - 1, -1):
upper = chr(char)
lower = chr(char + 32) # ASCII difference between uppercase and lowercase
if upper in seen and lower in seen:
return upper
return ""
# Test cases
print(greatestLetter("lEeTcOdE")) # Output: "E"
print(greatestLetter("arRAzFif")) # Output: "R"
print(greatestLetter("AbCdEfGhIjK")) # Output: ""
This solution ensures efficient performance even for large input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?