Find Smallest Letter Greater Than Target

You are given an array of characters letters sorted in non-decreasing order and a character target. letters contains at least two different characters. Return the smallest character in letters that is lexicographically greater than target. If no such character exists, return the first character in letters.

30:00

Find Smallest Letter Greater Than Target
easy
Free written solution
Topics
Companies

You are given an array of characters letters sorted in non-decreasing order and a character target. letters contains at least two different characters. Return the smallest character in letters that is lexicographically greater than target. If no such character exists, return the first character in letters.

Example 1:
Input: {"letters":["c","f","j"],"target":"c"}
Output: f
Constraints:
  • 2≤letters.length≤1042 \leq \text{letters.length} \leq 10^4

  • letters[i] is a lowercase English letter.

  • letters is sorted in non-decreasing order.

  • letters contains at least two different characters.

  • target is a lowercase English letter.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"letters":["c","f","j"],"target":"c"}

Find the first letter strictly after 'c'. The window [lo, hi) = [0, 3) includes the slot past the end, which stands for "no letter is bigger".

Sorted letters, split at 'c'

<= target

> target

c

0

lo

f

1

j

2

∅

end

hi

Why the answer wraps

abcdefghijklmnopqrstuvwxyzclockwise from'c'

Walk clockwise from the target and stop at the first letter that is in the list. Past 'z' the walk comes back to the smallest letter, which is why the code returns letters[lo % n].

Variables
VariableValue
lo0
hi3
targetc
DepthFunction Call
Stack empty
0/5