You're given a sorted array of numbers and a target value. Return the index of the target if it's in the array, or -1 if it isn't. This is the classic binary search — instead of scanning left to right (O(n)), you halve the search range on every step (O(log n)).
// Returns the index of `target` in `arr`, or -1 if not present.
// `arr` is sorted ascending. `arr` is not mutated.
function binarySearch(arr: number[], target: number): number;
binarySearch([1, 3, 5, 7, 9, 11], 7); // 3
binarySearch([1, 3, 5, 7, 9, 11], 1); // 0 (first element)
binarySearch([1, 3, 5, 7, 9, 11], 11); // 5 (last element)
binarySearch([1, 3, 5, 7, 9, 11], 4); // -1 (not present)
binarySearch([], 7); // -1 (empty array)
binarySearch([42], 42); // 0 (single element, hit)
binarySearch([42], 7); // -1 (single element, miss)
binarySearch([1, 2, 2, 2, 3], 2); // any of 1, 2, 3 — duplicates allowed
Math.floor((low + high) / 2) is the obvious midpoint, but on very large arrays low + high can overflow safe-integer range in other languages. In JS that's mostly theoretical, but the low + Math.floor((high - low) / 2) form is the standard idiom you'll see in interviews.Array.prototype.indexOf. That's O(n) and defeats the purpose of the exercise.