Greatest English Letter in Upper and Lower Case Problem
#2309
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2309.
Given a string of English letters s, 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.
An English letter b is greater than another letter a if b appears after a in the English alphabet.
Example 1:
Input: s = "lEeTcOdE"
Output: "E"
Explanation:
The letter 'E' is the only letter to appear in both lower and upper case.
Example 2:
Input: s = "arRAzFif"
Output: "R"
Explanation:
The letter 'R' is the greatest letter to appear in both lower and upper case.
Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.
Example 3:
Input: s = "AbCdEfGhIjK"
Output: ""
Explanation:
There is no letter that appears in both lower and upper case.
Constraints:
1 <= s.length <= 1000sconsists of lowercase and uppercase English letters.
Solution
Approach: Hash Table + Enumeration
Record which characters occur in s. Then check the letters from Z down to A: the first one whose uppercase and lowercase forms both occurred is the answer. If none, return an empty string.
Complexity: O(n) time and O(C) space, where n is the length of s and C the size of the character set.
from string import ascii_uppercase
class Solution:
def greatestLetter(self, s: str) -> str:
ss = set(s)
for c in ascii_uppercase[::-1]:
if c in ss and c.lower() in ss:
return c
return ''