Problem
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.
- For example, if target == ‘z’ and letters == [‘a’, ‘b’], the answer is ‘a’.
Algorithm
Binary Search.
Code
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
L, R = 0, len(letters)-1
while L < R:
Mid = (L + R) // 2
if letters[Mid] <= target:
L = Mid + 1
else: R = Mid
if letters[R] <= target:
return letters[0]
return letters[R]