Find Smallest Letter Greater Than Target

EasyBinary Searchbinary search

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array of lowercase letters letters, sorted in non-decreasing order and containing at least two distinct letters, and a lowercase letter target. Return the smallest letter in letters that is strictly greater than target. If no letter is greater than target, wrap around and return letters[0]. Letters may repeat. Aim for O(log n) time.

Examples

Input: letters = ["c","f","j"], target = "a"
Output: "c"
c is the first letter after a.
Input: letters = ["c","f","j"], target = "c"
Output: "f"
The answer must be strictly greater, so c itself is skipped.
Input: letters = ["x","x","y","y"], target = "z"
Output: "x"
Nothing exceeds z, so the search wraps to letters[0].

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search problems