Leetcode 2309. Greatest English Letter in Upper and Lower Case
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
?In the absence of explicit constraints or additional clarifications, we assume:
s
contains only English alphabetical letters.s
follows typical constraints you might find on competitive programming platforms, say up to (10^5) characters.To solve this problem, we can break it down into the following steps:
#include <iostream>
#include <unordered_set>
#include <string>
std::string greatestEnglishLetter(std::string s) {
std::unordered_set<char> lowercase_letters;
std::unordered_set<char> uppercase_letters;
// Populate the lowercase and uppercase sets
for (auto ch : s) {
if (islower(ch))
lowercase_letters.insert(ch);
if (isupper(ch))
uppercase_letters.insert(ch);
}
// Check from 'Z' to 'A' for the greatest letter that appears in both cases
for (char ch = 'Z'; ch >= 'A'; --ch) {
if (lowercase_letters.count(tolower(ch)) && uppercase_letters.count(ch)) {
return std::string(1, ch);
}
}
// Return empty string if no such letter exists
return "";
}
// Example usage
int main() {
std::string s = "lEeTcOdE";
std::cout << "Greatest English Letter: " << greatestEnglishLetter(s) << std::endl; // Output: "E"
return 0;
}
lowercase_letters
and uppercase_letters
can at most store 26 unique characters each, regardless of the input size.This solution is efficient given the constraints and should work well 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?