Find Smallest Letter Greater Than Target — LeetCode 744 Python Solution
- Problem
- #744
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is the length of `letters` |
| Space | O(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.