Find Smallest Letter Greater Than Target (LeetCode 744): Solution and Explanation
Given sorted letters and a target, return the first letter strictly after the target, wrapping to the first letter if none is bigger. An upper-bound binary search finds the boundary between letters <= target and letters > target in O(log n), and taking the index modulo n handles the wrap.
Intuition
In a sorted list, all letters that are <= target sit in a prefix and all letters > target sit in the suffix. The answer is the first element of that suffix.
Finding where a sorted array switches from 'no' to 'yes' is the classic job of binary search. Each probe tells us which side of the switch mid is on.
If the suffix is empty, the search ends one past the last index. Think of the alphabet as a circle: the next letter after the end is the smallest one, letters[0].
Approach: Upper-bound binary search with wrap-around
- Set lo = 0 and hi = n, a half-open window that includes the 'past the end' position.
- While lo < hi, take mid. If letters[mid] <= target, set lo = mid + 1.
- Otherwise letters[mid] is a candidate: set hi = mid to look for an earlier one.
- When the loop ends lo is the first index with a letter > target, or n if there is none.
- Return letters[lo % n].
Step-by-step example
letters = ["c","f","j"], target = "c"
- lo = 0, hi = 3, mid = 1. 'f' > 'c', so it is a candidate: hi = 1.
- mid = 0. 'c' <= 'c', so it is too small: lo = 1.
- lo = hi = 1. Return letters[1] = 'f'.
Code: Python, Java, C++
1class Solution:
2 def nextGreatestLetter(self, letters: List[str], target: str) -> str:
3 lo, hi = 0, len(letters)
4 while lo < hi:
5 mid = (lo + hi) // 2
6 if letters[mid] <= target:
7 lo = mid + 1
8 else:
9 hi = mid
10 return letters[lo % len(letters)]1class Solution {
2 public char nextGreatestLetter(char[] letters, char target) {
3 int lo = 0, hi = letters.length;
4 while (lo < hi) {
5 int mid = lo + (hi - lo) / 2;
6 if (letters[mid] <= target) {
7 lo = mid + 1;
8 } else {
9 hi = mid;
10 }
11 }
12 return letters[lo % letters.length];
13 }
14}1class Solution {
2public:
3 char nextGreatestLetter(vector<char>& letters, char target) {
4 int lo = 0, hi = (int)letters.size();
5 while (lo < hi) {
6 int mid = lo + (hi - lo) / 2;
7 if (letters[mid] <= target) {
8 lo = mid + 1;
9 } else {
10 hi = mid;
11 }
12 }
13 return letters[lo % letters.size()];
14 }
15};Time and space complexity
O(log n)
The half-open window halves on every comparison.
O(1)
Only lo, hi and mid are stored.
Other approaches
Linear scan (time O(n), space O(1))
Walk the array and return the first letter greater than target, or letters[0] at the end. Simple, and fine for small inputs.
Seen-letters table (time O(n + 26), space O(26))
Mark the 26 letters present, then step forward from target + 1 around the alphabet until a marked letter appears.
Common mistakes
- Using < instead of <= in the comparison. That finds the first letter >= target and returns the target itself when it is present.
- Starting with hi = n - 1. The search can then never report that no letter is bigger, and the wrap case returns the last letter instead of the first.
- Forgetting the wrap entirely and indexing letters[n], which is out of bounds.
Frequently asked questions
Why return letters[0] when nothing is bigger?
The problem treats the letters as wrapping around: after 'z' comes 'a' again. The smallest letter in the list is the first one you reach after wrapping.
Does it matter that letters can repeat?
No. Using <= target pushes lo past every copy of the target, so the result is the first letter that is strictly larger.
Is this the same as upper_bound or bisect_right?
Yes. bisect_right(letters, target) in Python returns the same index lo; you then return letters[lo % n].