Show problems as
Classic problem #744EasyArrayBinary Search

Find Smallest Letter Greater Than Target

Real-world version: Next Divider Label Round the Drawer
Tracked in this browser only
Read Find Smallest Letter Greater Than Target on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstBasic Binary Search · Binary Search, animated step by step

A filing drawer holds card dividers standing front to back. Each divider carries a single lowercase letter as its label, and letters lists those labels from front to back in non-decreasing order. Two dividers may carry the same label, but the drawer always shows at least two different labels.

You are also given a single lowercase letter target. Return the smallest label in the drawer that comes strictly after target in the alphabet.

If no label in the drawer comes after target, the search runs off the back of the drawer and continues from the front, so return the smallest label in the drawer instead. Return the label itself, not where it sits.

Examples

Example 1

Input
letters = ["c", "f", "j"], target = "d"
Output
"f"

Both `f` and `j` come after `d` in the alphabet, and `f` is the smaller of the two.

Example 2

Input
letters = ["c", "f", "j"], target = "j"
Output
"c"

No label in the drawer comes after `j`, so the search wraps to the front and gives the smallest label, which is `c`.

Example 3

Input
letters = ["b", "b", "d", "d", "f"], target = "b"
Output
"d"

The two `b` labels do not count, since the answer must come strictly after `b`. The smallest label that does is `d`.

Constraints

  • 2 <= letters.length <= 10^4
  • letters[i] is a lowercase English letter.
  • letters is sorted in non-decreasing order.
  • letters contains at least two different letters.
  • target is a lowercase English letter.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def next_greatest_letter(letters: list[str], target: str) -> str:
Java
public char nextGreatestLetter(char[] letters, char target)