Patterns / Pattern 4 of 5
Binary search
Halve the search space with every guess.
The 30-second version
A friend thinks of a number from 1 to 100. You guess 50, and they say "higher". In one guess, half the numbers are gone. Keep guessing the middle of what's left and you'll always find it in 7 guesses or fewer.
Binary search, in three steps:
- Look at the middle.
- Is the answer to the left or the right of it? Throw the other half away.
- Repeat until only the answer is left.
Think of it when a problem says:
- “the list is sorted”
- “the smallest number that works”
- “a huge list, find it fast”
- “the first or last place where…”
That’s the whole idea. The rest of this page shows it working, step by step.
Spot it when: The data is sorted, or the answer is a number you can test 'too big or too small'.
In one line: Look in the middle, throw away the wrong half.
Words on this page, in plain English (15)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Boolean (true or false)
- A value that can only be
trueorfalse. Like a light switch: on or off. - Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- Length
- How many items a list (or letters a string) has. The last position is always
length - 1. - If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Function
- A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
- Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Pattern
- A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
- Template
- The usual shape of a pattern's code. You fill in the parts that change for each problem.
- O(log n): logarithmic time
- The work grows very slowly, because each step throws away half. A million items need only about 20 steps.
- O(n): linear time
- The work grows in step with the input: twice the items, twice the work. One pass.
- Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
The guessing game
I'm thinking of a number from 1 to 100. Each time you guess, I say "higher" or "lower". The smart strategy is to guess 50: whatever I answer, half the numbers are gone. Then guess the middle of what's left, and again. You'll always find it in 7 guesses or fewer.
That's binary search: look at the middle, then throw away the half that can't contain the answer.
Watch it work: halve the search every step
sorted
- target =
- 52
- still in play =
- 12
Looking for 52. At first, all 12 numbers are in play.
Why it's so fast
Every step halves what's left. Starting from 1,000,000 items, after one step there are 500,000, then 250,000… After just 20 steps, one item remains. A billion items take about 30 steps.
This is O(log n): the number of times you can halve n before reaching 1. It grows incredibly slowly. Compare checking items one by one, which is O(n): a million steps instead of twenty.
Try it: how many halvings?
for (const n of [100, 1000, 1000000, 1000000000]) {
let steps = 0;
let left = n;
while (left > 1) {
left = Math.ceil(left / 2);
steps++;
}
console.log(n, "items:", steps, "steps");
}Press Run to see the output. You can change the code first.
Race: how much work as the input grows?
Check one by one O(n)1,000 steps · instant
Halve every time O(log n)10 steps · instant
Times assume a fast computer doing about 100 million simple steps a second.
The catch: it needs order
You can only throw away half when you know the answer can't be in it. In a sorted list, if the middle item is too small, everything to its left is smaller still, so it can all go. In an unsorted list you learn nothing about the other items, and binary search doesn't work.
The template
Keep a range from low to high that must contain the answer if it exists. Look at the middle. Shrink the range.
function search(sorted, target) { let low = 0; let high = sorted.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) return mid; if (sorted[mid] < target) { low = mid + 1; // the answer is to the right of mid } else { high = mid - 1; // the answer is to the left of mid } } return -1; // the range is empty: not found}Three details trip everyone up:
while (low <= high), with<=: a range of one item (low === high) still needs checking.mid + 1andmid - 1, notmid:midhas been checked, so leave it out. Forgetting this can loop forever.Math.floor: positions are whole numbers.
Binary search on the answer
Here's the twist that makes this pattern so powerful: you don't need a sorted list. You need a yes/no question that flips once.
"Can I finish this job at speed s?" is no for slow speeds and yes for fast ones, and once it's yes, it stays yes. So the smallest speed that works can be found by binary search over the speeds, even though there's no list at all.
function smallestThatWorks(low, high, works) { // `works(x)` is false, false, …, false, true, true, … as x grows. while (low < high) { const mid = Math.floor((low + high) / 2); if (works(mid)) { high = mid; // mid works: the answer is mid or smaller } else { low = mid + 1; // mid fails: the answer is bigger } } return low;}Notice this version uses low < high and high = mid (not mid - 1), because mid might be the answer. Both versions are correct; the key is to know which values your range still holds.
When to use it
- The input is sorted, and you're looking something up.
- The question is "the first / last / smallest / biggest value such that…", and the answer flips from no to yes just once.
- The input is huge (a billion), so even O(n) is too slow, but O(log n) is fine.
Common mistakes
- Off-by-one errors. Before writing the loop, decide: does my range include
high? Then make every line agree. - Infinite loops. If the range doesn't shrink every time (
low = midwithlow < high), it can get stuck. Check with a range of 2 items. - Using it on unsorted data. It will run and give wrong answers without complaint.
Learn it by heart
Understanding a pattern is the first half. The second is being able to write it without looking. Learn the recipe as words first, then each template in four steps. Your results go into your reviews, which bring each one back just before you’d forget it.
The recipe, out loud
- Keep a range:
lowandhigh. - Look at the middle:
mid = Math.floor((low + high) / 2). - If the answer can't be on one side of
mid, moveloworhighpast it. - The range halves every time, so it's O(log n).
Find an item in a sorted list
Use it for: Where is this value in a sorted list?
Learn it by heart: Find an item in a sorted list
Read the 14 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function search(sorted, target) { let low = 0; let high = sorted.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) return mid; if (sorted[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1;}Search on the answer
Use it for: The smallest number that works, when bigger numbers keep working.
Learn it by heart: Search on the answer
Read the 11 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function smallestThatWorks(low, high, works) { while (low < high) { const mid = Math.floor((low + high) / 2); if (works(mid)) { high = mid; } else { low = mid + 1; } } return low;}Practice problems
Easiest first. Each has hints and a full walkthrough.
| Solved | Problem | Difficulty |
|---|---|---|
| Find the number | easy | |
| Where it would go | easy | |
| Whole square root | easy | |
| First and last | medium | |
| Search a rotated list | medium | |
| Slowest speed that finishes | medium |
More patterns
- Stack
Keep the most recent unfinished thing on top, and finish it first.
- Hashing and counting
Remember what you have seen in a Map, so you never search for it twice.
- Two pointers
Walk through a list from both ends (or at two speeds) at once.
- Sliding window
Keep a stretch of the list and slide it along instead of starting over.
New to coding? Start with the JavaScript basics, or browse every practice problem.