All problems
0608EasyArrayBinary Search

Next Divider Label Round the Drawer

Tracked in this browser only
Write code

Trains the technique from

LeetCode 744Find Smallest Letter Greater Than Target

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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