Binary Search
Given a sorted array of distinct integers `nums` in ascending order and an integer `target`, search for `target` in `nums`. If `target` exists, return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. **Examples:** ```typescript binarySearch([-1, 0, 3, 5, 9, 12], 9) // 4 binarySearch([-1, 0, 3, 5, 9, 12], 2) // -1 binarySearch([5], 5) // 0 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(log n)
- Space complexity: O(1)
With each comparison, the search interval is cut in half. Halving an array of size n takes at most log2(n) steps, guaranteeing O(log n) logarithmic time.
Follow-Up Questions Interviewers Ask About Binary Search
- Why write `left + (right - left) / 2` instead of `(left + right) / 2`?
In languages with 32-bit signed integers (Java, C++, Rust), if `left + right` exceeds 2^31 - 1 (2,147,483,647), it causes integer overflow and turns negative, leading to out-of-bounds index errors. `left + (right - left) / 2` prevents overflow. - How does Binary Search change if the sorted array contains duplicates and you must find the FIRST occurrence?
When `nums[mid] === target`, do not immediately return `mid`. Instead, save `ans = mid` and continue searching the left half by setting `right = mid - 1` (Bisect Left). - Can Binary Search be used on a rotated sorted array (e.g. [4,5,6,7,0,1,2])?
Yes! At least one half of the array is always strictly sorted. You determine which half is sorted, check if the target falls within that sorted range, and narrow your search interval accordingly in O(log n) time.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.