Binary Search
Given an array of integers nums sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. Keep two bounds, low and high , and compare the target against the value at the midpoint each step, discarding the half that cannot hold it.
Constraints
- 1 ≤ nums.length ≤ 104
- -104 < numsi, target < 104
- All the integers in nums are unique
- nums is sorted in ascending order
Example
nums = [-1, 0, 3, 5, 9, 12], target = 94Explanation 9 exists in nums and its index is 4.
In plain terms
- O(log n)
- Grows so slowly that doubling the input only adds one more step — a million elements takes about twenty comparisons instead of a million.
Halve the search range until the target is found
low=0, high=5, mid=2 (value 3). 9 > 3, so low moves to 3.
What happens in this step
low=0, high=5 mid = 0 + floor((5-0)/2) = 2, nums[2] = 3 3 < 9, so the target must be to the right of mid — mid and everything left of it is discarded. low becomes 3.
Steps to visualize
- The row is the whole array; the box marks the part still being searched.
- Start low at index 0 and high at the last index.
- Compare numsmid to the target.
- If they match, return mid.
- If numsmid is smaller, move low to mid + 1.
- If numsmid is larger, move high to mid - 1.
- If low passes high, the target is not present — return -1.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
low=0, high=5, mid=2 (value 3). 9 > 3, so low moves to 3.
What happens in this step
low=0, high=5 mid = 0 + floor((5-0)/2) = 2, nums[2] = 3 3 < 9, so the target must be to the right of mid — mid and everything left of it is discarded. low becomes 3.
Solution
function search(nums, target) {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (nums[mid] === target) {
return mid;
}
if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}- Time
- O(log n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [-1, 0, 3, 5, 9, 12], target = 9 | 4 | example from the docstring |
nums = [-1, 0, 3, 5, 9, 12], target = 2 | -1 | target absent from the array |
nums = [5], target = 5 | 0 | smallest valid input, target present |
nums = [5], target = -5 | -1 | smallest valid input, target absent |
nums = [-1, 0, 3, 5, 9, 12], target = -1 | 0 | target is the first element |
nums = [-1, 0, 3, 5, 9, 12], target = 12 | 5 | target is the last element |
nums = [2, 5, 8, 12], target = 8 | 2 | even-length array with no exact middle |