Use upper-bound binary search for the first value greater than the target, then wrap the resulting index modulo the array length.
Complexity
O(log n) time and O(1) extra space.
Find the smallest sorted letter strictly greater than a target, wrapping to the first letter when necessary.
Use upper-bound binary search for the first value greater than the target, then wrap the resulting index modulo the array length.
O(log n) time and O(1) extra space.
package main
import "sort"
func nextGreatestLetter(letters []byte, target byte) byte {
index := sort.Search(len(letters), func(index int) bool { return letters[index] > target })
return letters[index%len(letters)]
}
from bisect import bisect_right
class Solution:
def nextGreatestLetter(self, letters: list[str], target: str) -> str:
return letters[bisect_right(letters, target) % len(letters)]
function nextGreatestLetter(letters: string[], target: string): string {
let left = 0;
let right = letters.length;
while (left < right) { const middle = left + Math.floor((right - left) / 2); if (letters[middle] <= target) left = middle + 1; else right = middle; }
return letters[left % letters.length];
}