Next Letter Up

EasyBinary Search≈ 15 min

A row of signs is labelled with letters, given as the string letters, sorted from a to z; a letter may appear more than once. Given a letter target, return the first letter in the row that comes after target in the alphabet.

The row wraps around: if no letter comes after target, the answer is the row's first letter.

Examples

text
letters = "cfj", target = "a"     →  "c"
letters = "cfj", target = "c"     →  "f"
letters = "cfj", target = "j"     →  "c"
letters = "eeegg", target = "e"   →  "g"

In the third example nothing comes after j, so the row wraps around to c. In the last, the es equal the target and do not count.

Constraints

  • Between 2 and 100,000 lowercase letters, sorted, with at least two different letters. target is one lowercase letter.
  • Aim for O(log n): a row four times longer should take only a couple of steps more.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.