Skip to content
BytePatterns

Next Letter After the Target

EasySearching#binary-search#upper-bound~15m

Problem

You are given a list of lowercase letters sorted in non-decreasing order, containing at least two different letters, and a target letter. Return the smallest letter in the list that is strictly greater than the target. If no letter is greater, wrap around and return the first letter of the list.

Examples

Input:  letters = ["c", "f", "j"], target = "a"
Output: "c"
Input:  letters = ["c", "f", "f", "j"], target = "f"
Output: "j"
Why:    strictly greater means both copies of f are skipped
Input:  letters = ["c", "f", "j"], target = "j"
Output: "c"
Why:    edge case, nothing is greater than j, so the answer wraps to the front

Hints

0 / 3

Stuck on the idea rather than the code? Binary Search Variants covers it.