#2309

Greatest English Letter in Upper and Lower Case

Easy
Hash TableStringEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach utilizes a set to track the characters seen in the string, allowing for efficient lookups. By iterating in reverse order (from 'Z' to 'A'), we can directly find the greatest letter that appears in both cases.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a set to store all characters in the string.
  2. 2Step 2: Iterate through the alphabet from 'Z' to 'A'.
  3. 3Step 3: For each letter, check if both the uppercase and lowercase versions are in the set.
  4. 4Step 4: Return the first letter found or an empty string if none exist.
solution.py8 lines
1# Full working Python code
2
3def greatestLetter(s):
4    seen = set(s)
5    for c in range(ord('Z'), ord('A') - 1, -1):
6        if chr(c) in seen and chr(c + 32) in seen:
7            return chr(c)
8    return ''

Complexity note: This complexity is efficient because we only iterate through the string once to build the set, and then we check the alphabet in constant time.

  • 1Using a set allows for O(1) average time complexity for lookups.
  • 2Iterating in reverse order ensures we find the greatest letter first.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.