I am trying to solve a question on Leetcode
Find Smallest Letter Greater Than Target
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.
For example, if
target == 'z'andletters == ['a', 'b'], the answer is 'a'.Example 1: Input: letters = ["c","f","j"], target = "a" Output: "c" Example 2: Input: letters = ["c","f","j"], target = "c" Output: "f" Example 3: Input: letters = ["c","f","j"], target = "d" Output: "f"Constraints:
2 <= letters.length <= 104 letters[i] is a lowercase English letter. letters is sorted in non-decreasing order. letters contains at least two different characters. target is a lowercase English letter.
My solution until now looks something like this:
function nextGreatestAlphabet(letters, target){
let left = 0;
let right = letters.length - 1;
let res = -1;
while(left <= right) {
let mid = Math.floor(left + (right - left) / 2);
if (letters[mid] == target ) { console.log(1)
res = letters[mid];
left = mid + 1;
}
if(letters[mid] > target){ console.log(2)
right = mid -1;
res = letters[mid];
}
if(letters[mid] < target ){ console.log(3)
left = mid + 1;
}
}
return res;
}
console.log(nextGreatestAlphabet(["c","f","j"],"c")); //c
But the correct result should be "f" as c is already present here and next greatest is f