function binarySearch(arr, target) {
let lo = 0, hi = arr.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] === target) return mid;
arr[mid] < target ? (lo = mid + 1) : (hi = mid - 1);
}
return -1;
}
binarySearch([1, 3, 5, 7], 5); // 2
binarySearch([1, 3, 5, 7], 4); // -1Binary search returns the index if found, or -1 if the target is not in the array.
This advanced exercise tests edge cases of binary search: ensuring it returns the exact index of the target, or -1 if not found. Pay attention to the correctness of the mid calculation and pointer adjustments.
Time Complexity: O(log n) Space Complexity: O(1)
function binarySearchStrict(arr: number[], target: number): number {
// Binary search that correctly handles all edge cases
// Must return exact index or -1
}
binarySearchStrict([1, 3, 5, 7, 9], 5) // 2
binarySearchStrict([1, 3, 5, 7, 9], 6) // -1