The simplest way to solve the problem is to iterate over the array and find the first character that is greater than the target character. If such a character is not found by the end of the array, the function should return the first character of the array. This approach simply checks each character in order from left to right, comparing it with the target.
Time Complexity: O(n) where n is the size of the array since each element may be checked in the worst case.
Space Complexity: O(1) as only a constant amount of space is used.
1#include <vector>
2using namespace std;
3
4char nextGreatestLetter(vector<char>& letters, char target) {
5 for (char letter : letters) {
6 if (letter > target) {
7 return letter;
8 }
9 }
10 return letters[0];
11}
The function checks each letter in the provided vector
. It returns the first letter that is greater than target
. If no such letter is found, it returns the first letter in the array, highlighting the circular nature of the list.
Utilizing the sorted nature of the array, we can employ a binary search technique to pinpoint the smallest character that exceeds the target. By continually narrowing the search range, we can efficiently determine the desired character. If the binary search concludes without finding a suitable character, the array's initial character is returned.
Time Complexity: O(log n), hinging on halving the array.
Space Complexity: O(1), processing is constant-space.
1#include <stdio.h>
2
3char nextGreatestLetter(char* letters, int lettersSize, char target) {
4 int low = 0, high = lettersSize - 1;
5 while (low <= high) {
6 int mid = low + (high - low) / 2;
7 if (letters[mid] <= target) {
8 low = mid + 1;
9 } else {
10 high = mid - 1;
11 }
12 }
13 return letters[low % lettersSize];
14}
This function relies on the binary search algorithm. The search confines focus to the mid-value, adjusting based on its comparison to target
. If mid
is greater, the search shifts left; otherwise, right. Upon termination, the remainder of low
mod lettersSize
returns the correct character for the circular case.