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 <stdio.h>
2
3char nextGreatestLetter(char* letters, int lettersSize, char target) {
4 for (int i = 0; i < lettersSize; i++) {
5 if (letters[i] > target) {
6 return letters[i];
7 }
8 }
9 return letters[0];
10}
The function iterates through each element in the letters
array. As soon as it finds a letter that is greater than target
, it returns that letter. If no such letter is found, it returns the first element of the array since the array is viewed in a circular manner.
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.
1function nextGreatestLetter(letters, target) {
2 let low = 0, high = letters.length - 1;
3 while (low <= high) {
4 let mid = Math.floor((low + high) / 2);
5 if (letters[mid] <= target) {
6 low = mid + 1;
7 } else {
8 high = mid - 1;
9 }
10 }
11 return letters[low % letters.length];
12}
A binary search function in Javascript that adjusts indices using the simple mathematical operations for binary comparison. Through modulus on low
, it resolves the correct wrap-based index for output.