Find Smallest Letter Greater Than Target — LeetCode 744 Python Solution

EasyArrayBinary Search
Problem
#744
Reading time
2 min

The problem

You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.

Example

Input
letters = ["c","f","j"], target = "a"
Output
"c"
Explanation
The smallest character that is lexicographically greater than 'a' in letters is 'c'.

Python solution

Python
class Solution:
    def nextGreatestLetter(self, letters: List[str], target: str) -> str:
        i = bisect_right(letters, ord(target), key=lambda c: ord(c))
        return letters[i % len(letters)]

Complexity

MeasureComplexity
TimeO(\log n), where n is the length of `letters`
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 744. Find Smallest Letter Greater Than Target is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 744. Find Smallest Letter Greater Than Target?
LeetCode 744. Find Smallest Letter Greater Than Target is rated Easy on LeetCode.
What is the time complexity of LeetCode 744. Find Smallest Letter Greater Than Target?
The Python solution on this page runs in O(\log n), where n is the length of `letters`.
What is the space complexity of LeetCode 744. Find Smallest Letter Greater Than Target?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 744. Find Smallest Letter Greater Than Target cover?
LeetCode 744. Find Smallest Letter Greater Than Target is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview