This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
50. search element right before target with Binary Search(possible duplicate array)
Solution:
We will use binary search to find the element right before first appearance of target number.
Here is the JavaScript code for the solution.
/**
* @param {number[]} nums - sorted ascending array with duplicate numbers
* @param {number} target
* @return {number|undefined}
*/
function binarySearchLastBefore(nums, target) {
let left = 0;
let right = nums.length - 1;
let index = -1;
while (left <= right) {
// middle index
const mid = Math.floor((left + right) / 2);
if (nums[mid] === target) {
// if mid index is target and mid index is not first element of array AND
// previous element to mid index is not target then return nums[mid-1]
if (mid > 0 && nums[mid-1] !== target) {
index = mid-1;
break;
} else {
// Otherwise try for the left half
right = mid-1;
}
} else if (nums[mid] < target) {
// Try for right half
left = mid+1;
} else {
// Try for left half
right = mid-1;
}
}
if (index !== -1) {
return nums[index];
}
return undefined;
}