Skip to content

Next Letter After the Target

Easy#binary-search#upper-bound~15 min

The mission

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

Target time
O(log n)
Target space
O(1)

Constraints

  • letters are lowercase and sorted non-decreasing
  • at least two different letters

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

Python 3Ctrl+Enter runs
Custom test case