Binary Search
Halve the search space every step. Trace low, mid, and high as they converge on the target.
You are searching a paper dictionary, not by flipping every page, but by opening it in the middle. If the word comes before that page, the entire second half is now irrelevant - throw it away. Each guess cuts what is left in half, so even a million entries costs you only about twenty page-flips.
Builds on
- Logarithms — the worst-case count is floor(log2 n) + 1, so you need to know that log2 of 1,000,000 is about 19.93.
- Big-O notation — the O(log n) bound and the O(1) space claim both rest on counting halvings and variables.
What is binary search?
binary search answers one question: is the target in this sorted array, and at which index? It looks at the middle element first. Because the array is sorted, one comparison tells you which half could still contain the target, and the other half can be discarded without being read.
| Method | Values checked | Probes | Needs sorted input? |
|---|---|---|---|
| Linear scan | 2, 5, 8, 12, 16 | 5 | no |
| binary search | 23, 8, 12, 16 | 4 | yes |
Check yourself
Which statement about binary search is true?
Where it shows up
Anywhere data is kept in sorted order, a lookup can halve: a sorted index in a database, the sorted keys inside each node of a B-tree, a commit history searched by git bisect, and a sorted list of timestamps searched for the version live at time T. binary search is also the building block for searches over a condition, where the search space is a range of candidate values instead of a stored array.
Check yourself
Which task is NOT a binary search over sorted data?
The intuition
Guess the middle. If nums[mid] is smaller than the target, every index up to mid holds a value that is smaller still, so the left side can be discarded. If nums[mid] is larger, the right side can be discarded. Either way mid itself is discarded too, because it was just checked.
Check yourself
You probe mid and find nums[mid] = 40, while the target is 25. Which part of the range can be discarded?
Complexity
Each probe removes mid and everything on one side, so the candidate range roughly halves each time. The worst case ends with a single element that still needs one more comparison, so the count is floor(log2 n) + 1 rather than log2 n. Counts below are the largest number of probes over every possible target, both present and absent.
| n | log2 n | floor(log2 n) + 1 | Worst case, checked in node |
|---|---|---|---|
| 7 | 2.81 | 3 | 3 |
| 1,000 | 9.97 | 10 | 10 |
| 1,024 | 10.00 | 11 | 11 |
| 1,000,000 | 19.93 | 20 | 20 |
function searchWithCount(nums, target) { let low = 0, high = nums.length - 1, probes = 0; while (low <= high) { const mid = Math.floor((low + high) / 2); probes++; if (nums[mid] === target) return { index: mid, probes }; if (nums[mid] < target) low = mid + 1; else high = mid - 1; } return { index: -1, probes };} function worstCase(n) { const nums = Array.from({ length: n }, (_, i) => i * 2); let worst = 0; for (let t = -1; t <= 2 * n; t++) worst = Math.max(worst, searchWithCount(nums, t).probes); return worst;} for (const n of [7, 1000, 1000000]) { console.log(n, worstCase(n), Math.floor(Math.log2(n)) + 1);}Check yourself
What is the worst-case number of comparisons for 1,024 sorted items?
The loop invariant
A loop invariant is a claim that stays true at every iteration. Here it is: if the target is in the array, its index lies inside [low, high]. Check it at three moments and the algorithm's correctness follows.
| Moment | What holds | Why |
|---|---|---|
| Start | low = 0 and high = n - 1, so the range covers every index | The whole array is the search space before any probe |
| Each iteration | The target, if present, stays inside [low, high] | nums[mid] is not the target, and the array is sorted, so the discarded half cannot hold it |
| Exit | The range is empty (low > high) | No index is left to hold the target, so the function returns -1 |
Termination is part of correctness. Every iteration either returns or moves low or high past mid, so the range shrinks by at least one item each time and the loop must end. Moving low to mid instead of mid + 1 would break that shrink step.
Check yourself
Which statement is the loop invariant of this search?
One hard rule
The discard step depends on order: when nums[mid] is too large, everything to its right is also too large. Without sorted order that inference fails, and the loop can discard the very half that holds the target. The function does not raise an error; it returns a wrong -1.
Check yourself
Search [1, 3, 2] for 2 with this loop. What does it return?
Exact match versus a condition
The loop here is an exact-match search: it stops as soon as nums[mid] equals the target. With duplicates it returns whichever matching index is probed first, which need not be the leftmost one. Searches that ask for the first index where a condition becomes true are a different template, with their own choice between lo < hi and lo <= hi. That template is taught in binary search on the answer and is not repeated here.
| Question asked | Returns | Template |
|---|---|---|
| Is 16 in this sorted array, and where? | index 4, or -1 | exact match (this lesson) |
| Where is the first value at least 10? | index of the first qualifying value | first-true (pattern lesson) |
| What is the smallest capacity that passes a check? | the smallest passing value | search over the answer (pattern lesson) |
Check yourself
Search [1, 4, 4, 4, 9] for 4 with the exact-match loop. Which index is returned?
Edge cases
The target may be missing, duplicated, or at either end. A correct implementation handles all three: a missing target leaves the range empty and returns -1, a duplicate returns some matching index, and both ends are reached because the loop tests low <= high rather than low < high.
Check yourself
When does the loop end without finding the target?
Midpoint overflow and JavaScript
The naive midpoint (low + high) / 2 forms a sum first. In a fixed-width integer that sum can overflow and wrap to a wrong value. JavaScript is different: every number is a double, which is exact for every integer up to 2^53 - 1 = 9,007,199,254,740,991. The largest possible array index is 2^32 - 2, so the largest sum is about 8.6 billion, far inside that limit. In JavaScript the naive midpoint is exact for any array.
| Language | Integer type | Is (low + high) / 2 safe? |
|---|---|---|
| JavaScript | double, exact up to 2^53 - 1 | yes, for every possible array index |
| Java or C with a 32-bit int | 32-bit signed, maximum 2,147,483,647 | no, once low + high passes 2^31 - 1, which needs indices near 2^30 (a billion) |
Write low + Math.floor((high - low) / 2) anyway. It reads as 'the middle of the gap', and it is the form that transfers safely to Java and C.
Check yourself
What is the largest safe integer in JavaScript, meaning every integer up to it is exact?
Interview script
01Restate (1 min)
Confirm the input is sorted and what to return on a miss, usually -1.
02Brute force (1 min)
A linear scan checks up to n values; for a million sorted items that is up to a million comparisons.
03Insight (2 min)
sorted order means one comparison discards half the remaining range.
04Code (5 min)
Set low and high, compute mid, compare, move low or high past mid, and loop while low <= high.
05Cost (2 min)
O(log n) time and O(1) space. Worst case is floor(log2 n) + 1 comparisons: 20 for a million items.
06Edges (1 min)
Empty array, missing target, duplicates, and the midpoint in a fixed-width language.
Recap
binary search finds a target in a sorted array by halving the range each step.
The data must be sorted. On an unsorted array the loop can return -1 for a value that is present.
Worst-case comparisons are floor(log2 n) + 1: 7 items take 3, 1,000 take 10, and 1,000,000 take 20.
The loop invariant: if the target is present, it lies inside [low, high]. An empty range (low > high) means the target is absent.
Use low + Math.floor((high - low) / 2) for the midpoint. JavaScript doubles are exact to 2^53 - 1, but 32-bit integers overflow.
First and last occurrences, and searches over a condition, use the templates in the pattern lesson.
Terms in this lesson
Every acronym and concept, expanded. Tap a term to open it.
time complexity
How an algorithm's number of operations grows with input size.
data structure
A way of organizing data in memory (array, tree, map) that determines which operations are fast.
binary search
Halving a sorted search space each step to find a value in O(log n).
linked list
A chain of nodes where each points to the next, giving cheap inserts and deletes but O(n) access.
call stack
The stack of active function calls the runtime tracks; each recursive call adds a frame.
algorithm
A precise, step-by-step procedure that solves a problem.
invariant
A statement that stays true before and after every loop iteration. Here: if the target is present, its index lies in [low, high].
latency
The time a single request takes from start to finish.
array
A contiguous block of memory holding items in order, readable by index in O(1).
stack
A last-in-first-out structure: you push on top and pop from the top.
node
One element in a linked structure, holding a value and pointers to its neighbors.
tree
A hierarchy of nodes where each node has one parent and zero or more children.
bit
A single 0 or 1 - the smallest unit of data.
sorted
Ordered smallest to largest - the one hard requirement binary search cannot work without.
halving
Cutting the search range in half at each step; the reason the algorithm is O(log n).
probe
One comparison of nums[mid] against the target. The worst-case cost is counted in probes.
midpoint
The middle index, computed as low + Math.floor((high - low) / 2) so the sum low + high is never formed.
logarithmic
Growing with the number of times you can halve n - log2(1,048,576) is 20.
integer overflow
When a sum such as low + high exceeds the largest value a fixed-width integer can hold, and wraps around to a wrong result.
double
The only number type in JavaScript: a 64-bit floating-point value, exact for every integer up to 2^53 - 1.
JSJavaScript
The language of this lesson's code samples. Its numbers are doubles, which is why the midpoint sum is exact here.
Where you will see it
Real systems that use this exact idea. Tap a card to open it.
Common traps
The mistakes interviewers watch for. Guess the fix, then reveal it.
FixUse low <= high. With strict <, a single-element range [i, i] never gets checked and targets at the last position are missed.
FixAlways move past mid: low = mid + 1 or high = mid - 1. Keeping mid in the range can stall the loop when the range narrows to two elements.
FixInteger overflow when low + high exceeds 2^31 - 1 in a 32-bit int. Use low + (high - low) / 2. This bug has appeared in widely used library code, so treat the naive form as a known trap.
FixThe shift truncates the sum to 32 bits, so past 2^31 - 1 the result is wrong: (2^31 + 2^31) >> 1 returns 0. Use Math.floor((low + high) / 2).
Interview prep
Questions you could be asked, with the depth an interviewer wants to hear.
Only on sorted data. If the input is not sorted, the discard-half logic is invalid and the result is wrong.
O(log n) · requires sorted data
Real worldDatabase indexes and git bisect both rely on this precondition.
DeeperIf you need binary search on unsorted data, you pay the sort cost first.