Find Smallest Letter Greater Than Target
Given a characters array letters sorted in non-decreasing order and a character target, return the smallest character in the array that is greater than the target. If no such character exists, wrap around and return the first character in the array. This is known as the ceiling of the target in circular array form.
A linear scan would check each character in O(n) time. Binary search improves this to O(log n) by finding the leftmost character greater than the target. If the target is greater than or equal to all characters, the answer wraps to index 0.
The binary search follows the standard pattern: compare the middle character with the target. If the middle character is greater than the target, search the left half for an even smaller character. Otherwise, search the right half. After the loop, lo is the insertion point. If lo equals the array length, wrap to index 0 using the modulo operator.
Edge cases include a single-character array (always return that character), target smaller than all characters (return the first), and target larger than all characters (wrap to first).
The upper bound binary search variant (lo < hi, narrowing to mid rather than mid-1 on success) finds the first element greater than the target. After the loop, lo is the insertion point: the index where target would be inserted to maintain sorted order. If lo equals the array length, the wrap-around rule ensures a non-empty result.
Example Input & Output
c is the first letter greater than a.
f is the smallest letter > c.
Single letter, a > a is false, wrap to a.
No letter > j, wrap to first letter c.
No letter > z, wrap to a.
Algorithm Flow

Solution Approach
Binary search for insertion point. After loop, return letters[lo % n] for wrap-around.
Time O(log n), Space O(1).
Best Answers
class Solution {
public char solution(char[] letters, char target) {
int lo = 0, hi = letters.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (letters[mid] > target) hi = mid;
else lo = mid + 1;
}
return letters[lo % letters.length];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
