Find Smallest Letter Greater Than Target, explained
To find the smallest letter strictly greater than a target in a sorted list, binary search for the first index whose letter is greater than the target (an upper bound), and wrap to index 0 when no such letter exists. That is O(log n) time and O(1) space, and in Python it is one call to bisect_right plus a modulo.
By Evin JohnPublished 7 min read
The problem in plain words
You receive a list of lowercase letters sorted alphabetically, possibly with repeats, and containing at least two different letters. You also receive a target letter, which may or may not be in the list. Return the smallest letter in the list that is strictly later in the alphabet than the target. If no letter is later, treat the list as circular and return its first letter.
| Target | Answer | Why |
|---|---|---|
| d | k | Both d entries are equal to the target, not greater, so skip past them |
| a | b | Everything is greater; the first letter wins |
| e | k | The target need not be in the list |
| p | b | Nothing is greater than p, so wrap around |
| z | b | Same wrap for a target past the end |
Two quick clarifications help. Is the comparison strictly greater, or greater than or equal? (Here it is strict.) And should the answer wrap, or return a sentinel when nothing is greater? The wrap is part of the standard statement, but it surprises people who skim.
Why interviewers like it
This is the upper-bound search in a small costume. Many candidates can write a binary search that finds an exact value, but fewer can write one that returns the first position past all copies of a value, which is what databases, schedulers and range queries use constantly. The wrap-around adds a second thing to keep in your head, and duplicates of the target punish any version that stops at the first match.
Slow approach: linear scan
Walk from the left and return the first letter that compares greater than the target. If the loop finishes, return the first letter. It is O(n) time and O(1) space, and it is correct. Since the list is sorted, the first greater letter you meet is also the smallest greater letter, which is the whole reason the binary search version works too.
def next_letter_scan(letters, target):
for ch in letters:
if ch > target:
return ch
return letters[0]Main approach: upper-bound binary search with wrap
Search over positions 0 to n, where n stands for the slot just past the end. Each step checks the middle letter. If it is less than or equal to the target, the answer lies to its right, so lo becomes mid + 1. If it is greater, it might be the answer or something to its left might be, so hi becomes mid. When lo meets hi, lo is the first index holding a letter greater than the target, or n if there is none. Taking lo modulo n turns that n into 0, which is exactly the wrap the problem asks for.
The comparison uses less than or equal on purpose. Sending equal letters to the right is what skips every copy of the target, so [b, d, d, k, p] with target d lands on k rather than on the second d.
def next_letter(letters, target):
lo, hi = 0, len(letters)
while lo < hi:
mid = (lo + hi) // 2
if letters[mid] <= target:
lo = mid + 1
else:
hi = mid
return letters[lo % len(letters)]from bisect import bisect_right
def next_letter_bisect(letters, target):
i = bisect_right(letters, target)
return letters[i % len(letters)]function nextLetter(letters, target) {
let lo = 0;
let hi = letters.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (letters[mid] <= target) lo = mid + 1;
else hi = mid;
}
return letters[lo % letters.length];
}If the interviewer accepts library calls, the bisect version is the cleanest answer in Python. Be ready to write the loop anyway, because the follow-up is often to explain what bisect_right does inside.
Trace: target d on [b, d, d, k, p]
- lo = 0, hi = 5mid = 2 holds d, which is not greater than d, so lo becomes 3.
- lo = 3, hi = 5mid = 4 holds p, which is greater, so hi becomes 4.
- lo = 3, hi = 4mid = 3 holds k, which is greater, so hi becomes 3. The loop ends with lo = 3, and the answer is k.
Complexity
| Approach | Time | Extra space | Note |
|---|---|---|---|
| Linear scan | O(n) | O(1) | Correct, ignores the sorting |
| Upper-bound binary search | O(log n) | O(1) | The expected answer |
| bisect_right in Python | O(log n) | O(1) | Same search, written by the library |
Since the alphabet has only 26 letters, some candidates point out that a 26-entry table would also answer in constant time per query after O(n) setup. That is a fair remark if many targets are queried against the same list, and worth mentioning as a trade-off.
Edge cases to test
- A target equal to the last letter: the answer wraps to the first letter.
- A target before the first letter: the answer is the first letter.
- Several copies of the target in a row, which must all be skipped.
- A target that falls between two letters in the list without matching either.
- A list of only two distinct letters with many repeats, such as [c, c, c, f, f].
Common mistakes
- Using less than instead of less than or equal, which returns a copy of the target instead of the next letter.
- Forgetting the wrap and indexing one past the end of the list.
- Setting hi to n - 1 and then having no way to signal that nothing was greater.
- Writing bisect_left in Python, which is the lower bound and lands on the target itself.
- Assuming letters are distinct and stopping at the first match.
How to explain it out loud
Fictional example
- Candidate
- This is an upper bound: the first position whose letter is strictly bigger than the target. The list is sorted, so I can binary search for it.
- Candidate
- I send anything less than or equal to the target to the right, so duplicates of the target get skipped. If the search ends at the length of the list, nothing was bigger, and modulo turns that into index zero for the wrap.
- Candidate
- That is log n time and constant space. In Python I could also call bisect_right and take the result modulo the length.
Related problems in this set
Arranging Coins runs the opposite search, the last value that passes a test, and shows why its midpoint rounds up. Relative Sort Array is the batch's ordering problem, a good change of pace after several searches. H-Index II uses the same first-true structure on numbers. For more patterns over sorted arrays, see the data structure interview questions.
Preparing with Natively
Natively can read a screenshot of a problem like this in a practice session and point to the search pattern it fits, giving you a reference to check your loop invariants against after your own attempt. Because it transcribes a mock round on your computer, you can read back whether you mentioned the wrap and the duplicate case before writing code. Read about an AI interview assistant for Mac and Windows.
Questions people ask
How do you find the smallest letter greater than the target?
Binary search for the first index whose letter is strictly greater than the target, searching positions 0 to n. Return letters[index % n], so an index of n wraps to the first letter.
Why use less than or equal in the comparison?
Letters equal to the target must be skipped, so they go to the right half. Using less than would stop on a copy of the target.
What does bisect_right do in this problem?
It returns the first position whose value is greater than the target, which is exactly the upper bound this problem needs. Take that index modulo the list length to handle the wrap.
What happens if no letter is greater than the target?
The answer wraps around to the first letter in the list, as if the letters were arranged in a circle.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
