JS Built-ins
Algorithmsadvanced

Binary Search Returns Correct Index or -1

πŸ“– Usage Example
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); // -1

Binary search returns the index if found, or -1 if the target is not in the array.

Binary Search Edge Cases

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
πŸ’‘ Hints (4)
  • β€’ Use bitwise right shift for mid calculation: `(left + right) >> 1` is equivalent to `Math.floor((left + right) / 2)`.
  • β€’ Ensure left and right pointers correctly narrow the search space.
  • β€’ The loop condition is `left <= right`.
  • β€’ After finding the target, return immediately.