Binary Search
Finding a word in a paper dictionary, you open near the middle and see which side the word falls on. The other half closes for good. Binary search works the same way: one comparison rules out half of what is left.
2 · Watch
Binary Search in 60 seconds
3 · Now you drive
Find Minimum in Rotated Sorted Array
4 · Your turn
Start from this
let lo = 0, hi = nums.length - 1;
// Stop when lo and hi meet on the answer.
while (lo < hi) {
// Rounds down, so mid is never hi.
const mid = Math.floor((lo + hi) / 2);
// mid is ruled out, so skip past it.
if (answerIsRightOf(mid)) lo = mid + 1;
// mid could be the answer, so keep it.
else hi = mid;
}
return lo;Easy ways to go wrong
- Setting lo = mid, which loops forever when lo and hi are neighbours.
- Mixing lo < hi with hi = mid - 1 without checking the last element.
- Assuming it needs a sorted array. It needs a yes/no that flips once.
- Searching on the answer with the wrong range. Koko’s speeds start at 1, and a split’s cap starts at the biggest number.
Find a position
Compare with the middle and keep the half that can still hold the answer.
- Easy01
Binary Search
The plain version: compare with the middle and drop half.
The array is sorted, so the middle value tells you which half the target is in.
- Time
- O(log n)
- Space
- O(1)
O(log n) time · O(1) spacefunction search(nums: number[], target: number): number { let lo = 0; let hi = nums.length - 1; while (lo <= hi) { const mid = (lo + hi) >> 1; if (nums[mid] === target) return mid; // The target is bigger, so everything up to mid is out. if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; } - Medium02
Search a 2D Matrix
Read the grid row by row as one long sorted list.
Row by row, the grid is one sorted list, so index mid maps to row mid / cols, column mid % cols.
- Time
- O(log(m·n))
- Space
- O(1)
O(log(m·n)) time · O(1) spacefunction searchMatrix(matrix: number[][], target: number): boolean { const cols = matrix[0].length; // Read the grid row by row as one sorted list of rows * cols numbers. let lo = 0; let hi = matrix.length * cols - 1; while (lo <= hi) { const mid = (lo + hi) >> 1; const value = matrix[Math.floor(mid / cols)][mid % cols]; if (value === target) return true; if (value < target) lo = mid + 1; else hi = mid - 1; } return false; } - Medium03
Find First and Last Position of Element in Sorted Array
Search twice: once for the first copy, once for the first bigger value.
Don’t stop at the first match. Keep halving to find the edge of the run of copies.
- Time
- O(log n)
- Space
- O(1)
O(log n) time · O(1) spacefunction searchRange(nums: number[], target: number): number[] { // The first index whose value is at least x, or nums.length if none is. const firstAtLeast = (x: number): number => { let lo = 0; let hi = nums.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (nums[mid] < x) lo = mid + 1; else hi = mid; } return lo; }; const first = firstAtLeast(target); if (first === nums.length || nums[first] !== target) return [-1, -1]; // The last copy sits just before the first value bigger than target. return [first, firstAtLeast(target + 1) - 1]; } - Medium04
Find Peak Element
No sorting needed: walk uphill and half the array drops away.
If the value after mid is bigger, a peak must lie to its right, because the climb has to stop somewhere.
- Time
- O(log n)
- Space
- O(1)
O(log n) time · O(1) spacefunction findPeakElement(nums: number[]): number { let lo = 0; let hi = nums.length - 1; while (lo < hi) { const mid = (lo + hi) >> 1; // Uphill to the right: the climb must top out somewhere past mid. if (nums[mid] < nums[mid + 1]) lo = mid + 1; // Downhill: mid itself, or something to its left, is a peak. else hi = mid; } return lo; }
Rotated arrays
One half around the middle is always in order. Work out which one first.
- Medium05
Find Minimum in Rotated Sorted Array
The one you just watched. Write it from memory.
Comparing the middle to the right end tells you which half holds the drop.
- Time
- O(log n)
- Space
- O(1)
- Medium06
Search in Rotated Sorted Array
Same halving, but first ask which half is sorted.
One half is always in order. Check whether the target sits inside it.
- Time
- O(log n)
- Space
- O(1)
Search on the answer
Guess an answer, check whether it works, and halve the range of answers.
- Medium07
Koko Eating Bananas
Halve the possible answers, not the input.
If a speed is fast enough, every faster speed is too. That yes/no flips once.
- Time
- O(n log m)
- Space
- O(1)
O(n log m) time · O(1) spacefunction minEatingSpeed(piles: number[], h: number): number { // Every speed from 1 to the biggest pile is a possible answer. let lo = 1; let hi = Math.max(...piles); while (lo < hi) { const k = Math.floor((lo + hi) / 2); let hours = 0; for (const p of piles) hours += Math.ceil(p / k); if (hours <= h) hi = k; // fast enough: try slower else lo = k + 1; // too slow: go faster } return lo; } - Hard08
Split Array Largest Sum
Guess the largest sum, then check greedily how many pieces it needs.
Checking a cap is easy: fill each piece until it would overflow. A bigger cap never needs more pieces.
- Time
- O(n log s)
- Space
- O(1)
Also works with Greedy.
O(n log s) time · O(1) spacefunction splitArray(nums: number[], k: number): number { // How many pieces do we need if no piece may add up to more than cap? const piecesFor = (cap: number): number => { let pieces = 1; let sum = 0; for (const x of nums) { if (sum + x > cap) { pieces++; sum = 0; } sum += x; } return pieces; }; // The answer is at least the biggest number and at most the whole sum. let lo = Math.max(...nums); let hi = nums.reduce((a, b) => a + b, 0); while (lo < hi) { const cap = Math.floor((lo + hi) / 2); if (piecesFor(cap) <= k) hi = cap; // k pieces are enough: try a smaller cap else lo = cap + 1; } return lo; } - Hard09
Median of Two Sorted Arrays
Search for where to cut the shorter array, so both left parts make half.
Taking i from the first array fixes how many come from the second. Check the four values at the cut.
- Time
- O(log min(m, n))
- Space
- O(1)
O(log min(m, n)) time · O(1) spacefunction findMedianSortedArrays(nums1: number[], nums2: number[]): number { // Binary search the shorter array. const [a, b] = nums1.length <= nums2.length ? [nums1, nums2] : [nums2, nums1]; const m = a.length; const n = b.length; const half = Math.floor((m + n + 1) / 2); let lo = 0; let hi = m; while (lo <= hi) { // The left half takes i values from a and the rest from b. const i = (lo + hi) >> 1; const j = half - i; const aLeft = i > 0 ? a[i - 1] : -Infinity; const aRight = i < m ? a[i] : Infinity; const bLeft = j > 0 ? b[j - 1] : -Infinity; const bRight = j < n ? b[j] : Infinity; if (aLeft <= bRight && bLeft <= aRight) { // A clean cut: everything on the left is at most everything on the right. const leftMax = Math.max(aLeft, bLeft); if ((m + n) % 2 === 1) return leftMax; return (leftMax + Math.min(aRight, bRight)) / 2; } if (aLeft > bRight) hi = i - 1; // took too many from a else lo = i + 1; // took too few from a } throw new Error("The arrays must be sorted."); }