Pattern 03 / 10 · Fundamentals
Binary Search
Halve the search space every step until only the answer is left.
The idea
Keep a range [lo, hi] that must contain the answer. Look at the middle: it either is the answer, or it proves the whole left or right half can be thrown away. The range halves every step.
time O(log n)space O(1)
Reach for it when
- The data is sorted, or the answer space is monotonic (false… false, true… true).
- You need O(log n) instead of a linear scan.
- The problem asks for the first or last position where something becomes true.
Watch it run
704. Binary Search
Return the index of target in a sorted array, or -1 if it is not there.
Example 1
Input: nums = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4.
Example 2
Input: nums = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1.
WALKTHROUGH INPUT · nums = [-1, 0, 3, 5, 9, 12, 15, 20], target = 12
lo
-1
00
13
25
39
412
515
6hi
20
7target = 12range size = 8
The answer, if it exists, is somewhere in [0, 7].
1function search(nums: number[], target: number): number {2let lo = 0, hi = nums.length - 1;3while (lo <= hi) {4const mid = Math.floor((lo + hi) / 2);5if (nums[mid] === target) return mid;6if (nums[mid] < target) lo = mid + 1;7else hi = mid - 1;8}9return -1;10}