Leetcode 744. Find Smallest Letter Greater Than Target
Given a list of sorted characters letters
containing only lowercase letters, and a target letter target
, find the smallest element in the list that is greater than the given target.
Letters also wrap around. For example, if the target is z
and letters
contains letters from a
to c
, the answer is a
.
You can assume:
letters
has at least two characters.letters
is sorted in non-decreasing order.letters
contains only lowercase English letters from a
to z
.letters
is guaranteed to be non-decreasingly sorted and contains at least two characters.letters
contain duplicate characters?
letters
can contain duplicate characters.To solve this problem efficiently, we can use a Binary Search algorithm due to the sorted nature of the letters
list. The steps will be:
target
.Here’s the C++ implementation:
#include <vector>
#include <iostream>
char nextGreatestLetter(std::vector<char>& letters, char target) {
int left = 0;
int right = letters.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (letters[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// Element at 'left' is the smallest element greater than target,
// or the element is wrap around the list
return letters[left % letters.size()];
}
int main() {
std::vector<char> letters = {'c', 'f', 'j'};
char target = 'd';
std::cout << "The smallest letter greater than " << target << " is " << nextGreatestLetter(letters, target) << std::endl;
return 0;
}
The time complexity of this algorithm is O(log n) due to the binary search mechanism.
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?