Leetcode 744. Find Smallest Letter Greater Than Target
Leetcode 744: Find Smallest Letter Greater Than Target
Given a list of sorted characters letters
containing only lowercase letters, and a target character target
, the task is to find the smallest character in the list that is larger than the given target character. If no such character exists, you should return the first character in the list.
letters = ["c","f","j"], target = "a"
"c"
letters = ["c","f","j"], target = "c"
"f"
letters = ["x","x","y","y"], target = "z"
"x"
2 <= letters.length <= 10^4
letters
consists of lowercase English letters.letters
is sorted in non-decreasing order.letters
contains at least two different characters.letters
contain duplicate letters?
To find the smallest character greater than the target, we can use a binary search approach due to the following reasons:
letters
is sorted, which makes binary search an optimal choice.Here is the plan:
low
to 0 and high
to the length of the list.mid
.letters[mid]
is less than or equal to target
, move the low
pointer to mid + 1
.letters[mid]
is greater than target
, move the high
pointer to mid
.low
pointer should be at the smallest character that is greater than the target. If low
reaches the end of the list, wrap around to the first character.public class Solution {
public char nextGreatestLetter(char[] letters, char target) {
int low = 0;
int high = letters.length;
// Perform binary search
while (low < high) {
int mid = low + (high - low) / 2;
if (letters[mid] <= target) {
low = mid + 1;
} else {
high = mid;
}
}
// Since the array is circular
return letters[low % letters.length];
}
}
The time complexity of this approach is (O(\log n)) due to the binary search algorithm, where (n) is the length of the letters
array.
The space complexity is (O(1)) as we are using only a fixed amount of additional space regardless of the input size.
This approach ensures that we efficiently and correctly determine the smallest character greater than the given target in the sorted list.
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?