Given an array of characters letters
that is sorted in non-decreasing order and a character target
, your task is to find the smallest character in the array that is lexicographically greater than target
. If such a character does not exist, return the first character in the array.
You can assume that:
letters
has at least 2 characters.letters
are in lowercase and are sorted in non-decreasing order.target
is a lowercase letter.target
character be in the letters
array?
letters
are less than or equal to target
?
letters
array are less than or equal to target
, return the first character in the array.letters
array?
target
, a binary search algorithm can be employed because the letters
array is sorted.target
by circular array logic.def nextGreatestLetter(letters, target):
left, right = 0, len(letters) - 1
# Check if all characters are less than or equal to target
if target >= letters[-1]:
return letters[0]
while left < right:
mid = (left + right) // 2
if letters[mid] <= target:
left = mid + 1
else:
right = mid
return letters[left]
# Example usage
letters = ["c", "f", "j"]
target = "a"
print(nextGreatestLetter(letters, target)) # Output: "c"
target
is greater than or equal to the last character in letters
, return the first character in letters
.left
and right
pointers to the start and end of the array.letters[mid]
is less than or equal to target
, search in the right half by setting left = mid + 1
.right = mid
.left
and right
point to the same index, which will be the smallest character greater than target
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?