Find Smallest Letter Greater Than Target in Python

Given a sorted list of lowercase letters, we need to find the smallest letter that is greater than a target letter. The letters wrap around, so if no letter is greater than the target, we return the first letter in the list.

For example, if we have letters ["c", "f", "j"] and target "a", the answer is "c". If the target is "z" and letters are ["a", "b"], the answer wraps around to "a".

Using Binary Search

Since the letters are already sorted, we can use binary search to find the smallest letter greater than the target efficiently ?

def nextGreatestLetter(letters, target):
    left = 0
    right = len(letters) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if letters[mid] > target:
            right = mid - 1
        else:
            left = mid + 1
    
    # If no letter is greater, wrap around to the first letter
    return letters[left % len(letters)]

# Test with different examples
print(nextGreatestLetter(["c", "f", "j"], "a"))
print(nextGreatestLetter(["c", "f", "j"], "c"))
print(nextGreatestLetter(["c", "f", "j"], "d"))
print(nextGreatestLetter(["c", "f", "j"], "k"))
print(nextGreatestLetter(["a", "b"], "z"))
c
f
f
c
a

How It Works

The algorithm uses binary search to efficiently find the target position:

  • Left and Right pointers: Track the search boundaries
  • Mid calculation: Find the middle element to compare
  • Comparison: If letters[mid] > target, search left half; otherwise, search right half
  • Wrap-around: Use modulo operator to handle cases where no letter is greater than target

Alternative Linear Approach

For smaller arrays, a simple linear search can also work ?

def nextGreatestLetterLinear(letters, target):
    for letter in letters:
        if letter > target:
            return letter
    # If no letter found, return the first letter (wrap around)
    return letters[0]

# Test the linear approach
print(nextGreatestLetterLinear(["c", "f", "j"], "a"))
print(nextGreatestLetterLinear(["c", "f", "j"], "k"))
c
c

Time Complexity Comparison

Method Time Complexity Space Complexity Best For
Binary Search O(log n) O(1) Large sorted arrays
Linear Search O(n) O(1) Small arrays or unsorted data

Conclusion

Binary search provides an efficient O(log n) solution for finding the next greatest letter in a sorted array. The modulo operation elegantly handles the wrap-around requirement when no letter is greater than the target.

Updated on: 2026-03-25T08:48:45+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements