Task 1: Greatest English Letter
You are given a string, $str, made up of only alphabetic characters [a..zA..Z].
Write a script to return the greatest English letter in the given string.
A letter is greatest if it occurs as both lower and upper case. Also letter 'b' is greater than 'a' if 'b' appears after 'a' in the English alphabet. If no such letter exists, return an empty string.
Example 1: Input: $str = 'PeRlwEeKLy' → Output: 'L'
Example 2: Input: $str = 'ChaLlenge' → Output: 'L'
Example 3: Input: $str = 'The' → Output: ''
Method Explanation
The problem asks for the lexicographically largest letter in the English alphabet that appears in the input string in both lowercase and uppercase forms.
Our approach separates character observations by case:
- Scan the input string and record which letters appear in lowercase and which appear in uppercase.
- Compute the intersection of both sets of letters (normalized to lowercase).
- If the intersection is non-empty, find the maximum letter alphabetically and return its uppercase representation; otherwise return an empty string
''.
This runs in $O(N)$ time where $N$ is the length of the string, and $O(1)$ space since the alphabet has at most 26 letters.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
signature_for greatest_english_letter => (
method => 0,
positional => [Str],
);
sub greatest_english_letter ($str) {
my %seen;
for my $char ( split //, $str ) {
if ( $char =~ /^[A-Z]$/ ) {
$seen{ lc $char }{upper} = 1;
}
elsif ( $char =~ /^[a-z]$/ ) {
$seen{ lc $char }{lower} = 1;
}
}
my $greatest_letter = '';
for my $letter ( keys %seen ) {
if ( $seen{$letter}{upper} && $seen{$letter}{lower} ) {
$greatest_letter = $letter if $letter gt $greatest_letter;
}
}
return uc $greatest_letter;
}
Python Solution
def greatest_english_letter(s: str) -> str:
"""Return the greatest English letter occurring in both lower and upper case."""
lower_set = {c.lower() for c in s if c.islower()}
upper_set = {c.lower() for c in s if c.isupper()}
common_letters = lower_set & upper_set
greatest_letter = max(common_letters, default="")
return greatest_letter.upper()