Length 2:01Binary search: how it works and when to use it
Binary search halves a sorted range at every step, so a million items take about 20 checks. Signals, a worked 2D grid example, code and practice.
On this page
The video
Search a 2D Matrix
LeetCode 74Open the video page
Chapters
- Play from 0:00The problem and its rules
- Play from 0:12Two quick examples
- Play from 0:23Checking every cell is slow
- Play from 0:35Read the grid as one list
- Play from 0:47From position to row and column
- Play from 1:02Searching for sixteen
- Play from 1:22The code in JavaScript
- Play from 1:40Recap: time and memory
Transcript
Show the whole transcriptHide the transcript
- Play from 0:00
LeetCode 74 asks you to find one target number in a grid.
- Play from 0:04
Each row is sorted from small to large.
- Play from 0:07
And the first number of every row is bigger than the last number of the row above.
- Play from 0:12
Here is the example from the problem, with three rows and four columns.
- Play from 0:16
Is the number 3 in the grid?
- Play from 0:18
Yes, so we return true.
- Play from 0:19
Is 13 in the grid?
- Play from 0:21
No, so we return false.
- Play from 0:23
The easy answer checks every cell one by one.
- Play from 0:26
With m rows and n columns, that takes m times n checks.
- Play from 0:30
The problem wants something faster, a running time of log of m times n.
- Play from 0:35
Here is the idea.
- Play from 0:36
Read the rows one after another, and you get one long sorted list.
- Play from 0:40
It has twelve numbers, at positions zero to eleven.
- Play from 0:43
A sorted list means we can use binary search.
- Play from 0:47
We never build that list.
- Play from 0:48
We turn a position into a row and a column instead.
- Play from 0:52
The row is the position divided by n, rounded down.
- Play from 0:55
The column is the remainder.
- Play from 0:57
Position six, with four columns, is row one, column two.
- Play from 1:00
That cell holds sixteen.
- Play from 1:03
Now we search for sixteen.
- Play from 1:04
Low starts at zero, and high starts at eleven.
- Play from 1:07
The middle is position five, which holds eleven.
- Play from 1:10
That is too small, so low moves to six.
- Play from 1:12
The new middle is eight, which holds twenty three.
- Play from 1:15
That is too big, so high moves to seven.
- Play from 1:17
The middle is six, which holds sixteen.
- Play from 1:19
We found it in three steps.
- Play from 1:22
Here is the code in JavaScript.
- Play from 1:24
We store the row and column counts, and set low and high.
- Play from 1:27
While low is not bigger than high, we find the middle.
- Play from 1:30
We turn it into a row and a column, and read the value.
- Play from 1:33
We return true on a match, and otherwise move low or high.
- Play from 1:37
If the loop ends, the target is not in the grid.
- Play from 1:41
Each step cuts the search space in half.
- Play from 1:43
So the time is log of m times n, and the extra memory stays constant.
- Play from 1:48
Treat the grid as one sorted list, and binary search it with a division and a remainder.
Binary search finds an item in a sorted list by looking in the middle. If the middle is too small, the answer must be in the right half. If it's too big, the answer must be in the left half. Either way, half of the list is gone after one check. Repeat until you find it or nothing is left. A sorted list of a million items takes at most 20 checks.
The idea in one minute
Think of looking up a word in a paper dictionary. You don't read every page. You open it near the middle, see that your word comes later, and ignore the first half. Then you do the same with what's left.
Binary search does the same with two markers:
lowis the first position that could still hold the answer.highis the last position that could still hold the answer.
Each step looks at the middle position between them and moves one marker past it. The range between low and high halves every time. When low passes high, the range is empty, so the item isn't there.
This only works because the list is sorted. Sorted order is what tells you which half to throw away.
When to use it
Look for these signals:
- The input is sorted, or sorted in pieces you can tell apart.
- The problem asks for a running time of O(log n). Big-O notation describes how the work grows with the input. O(log n) means it grows with the number of times you can halve the input, which is very slowly. Few other tools reach that, so it's a strong hint.
- You want the first or last position where something becomes true. "The first number that is at least 5." "The last day the shop is still open."
- Binary search on the answer. The answer is a number, and you can write a yes-or-no check that flips once. Small values fail and big values pass, or the other way round. Then you can binary search over the possible answers, even when there is no list at all.
A worked example
This is the example from the video. It is LeetCode 74, Search a 2D Matrix. In our words: you get a grid of numbers. Each row is sorted from small to large. The first number of each row is bigger than the last number of the row above. Is a target number in the grid?
Here is the grid, with 3 rows and 4 columns:
1 3 5 7
10 11 16 20
23 30 34 60
See one sorted list
Read the rows one after another. You get one long sorted list of 12 numbers, at positions 0 to 11. So we can binary search it.
We never build that list. Instead, we turn a position into a row and a column. With n columns:
- the row is the position divided by
n, rounded down; - the column is the remainder of that division.
Take position 6, with 4 columns. 6 divided by 4 is 1, with 2 left over. So it's row 1, column 2. That cell holds 16.
Search for 16
| low | high | middle | row, column | value |
|---|---|---|---|---|
| 0 | 11 | 5 | 1, 1 | 11 |
| 6 | 11 | 8 | 2, 0 | 23 |
| 6 | 7 | 6 | 1, 2 | 16 |
- Step 1. The middle of 0 and 11 is 5. Position 5 holds 11, which is too small. So
lowmoves to 6. - Step 2. The middle of 6 and 11 is 8. Position 8 holds 23, which is too big. So
highmoves to 7. - Step 3. The middle of 6 and 7 is 6. Position 6 holds 16. Found, after 3 checks.
If we searched for 13 instead, the range would shrink until low passed high, and we'd answer false.
The code in JavaScript
The 2D grid
function searchMatrix(matrix, target) {
const m = matrix.length; // rows
const n = matrix[0].length; // columns
let low = 0;
let high = m * n - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const value = matrix[Math.floor(mid / n)][mid % n]; // row, column
if (value === target) return true;
if (value < target) low = mid + 1;
else high = mid - 1;
}
return false;
}
const grid = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]];
searchMatrix(grid, 16); // true
searchMatrix(grid, 13); // false
The first position that is big enough
Often you don't want "is it there?" but "where does it start?". This version finds the first position whose value is at least target. If every value is smaller, it returns the list's length, which is where target would be added.
function firstAtLeast(sorted, target) {
let low = 0;
let high = sorted.length; // one past the end: "not found yet"
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (sorted[mid] < target) low = mid + 1; // the answer is to the right
else high = mid; // mid might be the answer, so keep it
}
return low;
}
firstAtLeast([1, 3, 3, 3, 8], 3); // 1, the first 3
firstAtLeast([1, 3, 3, 3, 8], 4); // 4, where a 4 would go
Binary search on the answer
The same loop works on numbers instead of a list. Here, works(x) is a yes-or-no check that is false for small x and true from some point on. The loop finds that point.
function firstThatWorks(low, high, works) {
// Assumes works(high) is true.
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (works(mid)) high = mid;
else low = mid + 1;
}
return low;
}
firstThatWorks(0, 100, (x) => x * x >= 50); // 8, since 7 * 7 = 49 and 8 * 8 = 64
How fast is it?
Programmers describe speed with Big-O notation. It says how the work grows as the input grows. O(n) means the work grows in step with n, the number of items.
Binary search is O(log n). Here, log n means how many times you can halve n before you reach 1. It grows very slowly:
| items | most checks needed |
|---|---|
| 12 | 4 |
| 1,000,000 | 20 |
| 1,000,000,000 | 30 |
- Time for the grid: O(log(m × n)), where
mis the number of rows andnthe number of columns. Checking every cell would take O(m × n). - Memory: O(1). The loop keeps a few numbers, however big the grid is.
- Binary search on the answer costs O(log of the range) checks, times the cost of one check.
Common mistakes
- Searching a list that isn't sorted. The loop runs and returns an answer, but the answer means nothing.
- Mixing loop styles.
while (low <= high)goes withlow = mid + 1andhigh = mid - 1.while (low < high)goes withhigh = mid. Mixing them leads to a loop that never ends, or that skips the answer. - Moving a marker to
midinstead of past it. In the<=style,low = midcan repeat the same step forever whenlowandhighare next to each other. - Dividing by the wrong count in the grid. The row is the position divided by the number of columns, not rows. With a square grid both work, which hides the bug until a test has a different shape.
- Overflow in other languages. In Java or C++,
low + highcan be too big for a whole number type. Writelow + (high - low) / 2there. JavaScript numbers are exact up to about 9 thousand trillion, soMath.floor((low + high) / 2)is fine for any list. - An empty input.
matrix[0].lengthfails if there are no rows. The problem promises at least one row, but real code should check.
Practice problems
- LeetCode 704, Binary Search. The plain version. Write it from memory.
- LeetCode 35, Search Insert Position. The
firstAtLeastidea. - LeetCode 34, Find First and Last Position of Element in Sorted Array. Two searches: the first position and the last.
- LeetCode 153, Find Minimum in Rotated Sorted Array. Compare the middle with the right end to pick a half.
- LeetCode 33, Search in Rotated Sorted Array. One half is always sorted. Work out which one.
- LeetCode 875, Koko Eating Bananas. Binary search on the answer, with
firstThatWorks.
In short
Binary search throws away half of a sorted range at every step, so the work grows with log n instead of n. For a sorted grid, treat it as one long list, and turn each position into a row and a column with a division and a remainder.
Want a video for a different problem?
Type a problem, a pattern or a system to design. You get a narrated video like the one above, usually ready in 5 to 9 minutes.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video