Binary Search
How binary search finds a value or a boundary in sorted data in O(log n) time, how to handle duplicates, and what interviewers ask about it.
On this page
Binary search finds a position in sorted data by repeatedly checking the middle element and discarding the half that cannot contain the answer. It takes O(log n) time, where a linear scan takes O(n). You reach for it when the input is sorted, or when the question can be answered with a yes or no that switches from "no" to "yes" exactly once along the input.
How binary search works
The most useful form of binary search finds the lower bound of a target: the first index whose value is greater than or equal to the target. In a sorted array, asking "is this value at least the target?" gives a run of "no" answers followed by a run of "yes" answers, and the lower bound is the position of the first "yes".
The lower bound answers several questions at once. If the value at that index equals the target, it is the first occurrence of the target. If it does not, the target is missing, and the index is the place where the target would be inserted to keep the array sorted. If every answer is "no", the lower bound is n, one past the end of the array.
The search keeps two indexes, lo and hi. Every position before lo is known to be a "no", and every position from hi onward is known to be a "yes". The positions in [lo, hi), which includes lo and excludes hi, are still undecided. Each step looks at the middle of that range. If the middle is a "no", the search moves lo past it. If the middle is a "yes", the search moves hi down to it. When lo and hi meet, no positions are undecided, and lo is the first "yes".
The trace below searches for 8, which appears three times. When the search lands on an 8 it does not stop, because an earlier 8 might exist, so it keeps narrowing toward the left.
lo = 0, hi = nwhile lo < hi: mid = lo + (hi - lo) // 2 if a[mid] < target: lo = mid + 1 else: hi = midreturn lo- a03lo182838412515620727hi
- target
- 8
- checks
- 0
1The answer can be any index from 0 to 8, where 8 means that every value is smaller than the target. So
histarts atn, one past the end. - a03lo182838412mid515620727hi
- target
- 8
- checks
- 1
2The middle is 0 + (8 − 0) // 2 = 4, and
a[4]is 12. - a03lo182838412hi515620727
- target
- 8
- checks
- 1
312 is at least 8, so this is a "yes". Position 4 might be the first "yes", but nothing after it can be, so the search sets
hi = mid. - a03lo1828mid38412hi515620727
- target
- 8
- checks
- 2
4The middle is 0 + (4 − 0) // 2 = 2, and
a[2]is 8. - a03lo1828hi38412515620727
- target
- 8
- checks
- 2
5This is another "yes". The search has found an 8 but cannot tell whether it is the first one, so it does not return. It sets
hi = 2and keeps looking to the left. - a03lo18mid28hi38412515620727
- target
- 8
- checks
- 3
6The middle is 0 + (2 − 0) // 2 = 1, and
a[1]is 8. - a03lo18hi2838412515620727
- target
- 8
- checks
- 3
7This is a "yes" again, so
hi = 1. Only position 0 is still undecided. - a03lo mid18hi2838412515620727
- target
- 8
- checks
- 4
8The middle is 0 + (1 − 0) // 2 = 0, and
a[0]is 3. - a0318lo hi2838412515620727
- target
- 8
- checks
- 4
93 is smaller than 8, so this is a "no". Position 0 is ruled out, and the search sets
lo = mid + 1 = 1. - a0318lo hi2838412515620727
- returns
- 1
- checks
- 4
10Now
loequalshi, so no positions are undecided, and the first 8 is at index 1. The search made 4 checks for 8 items.
Code for the lower bound
Most binary searches on arrays are this function, or a small change to its comparison.
// First index i with a[i] >= target, or a.length if there is none.
// a must be sorted from low to high.
function lowerBound(a, target) {
let lo = 0;
let hi = a.length; // half-open range [lo, hi)
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (a[mid] < target) lo = mid + 1; // mid is a "no": answer is right of it
else hi = mid; // mid is a "yes": answer is mid or left
}
return lo; // lo === hi
}
function contains(a, target) {
const i = lowerBound(a, target);
return i < a.length && a[i] === target;
}
lowerBound([3, 8, 8, 8, 12, 15, 20, 27], 8); // 1# First index i with a[i] >= target, or len(a) if there is none.
# a must be sorted from low to high.
def lower_bound(a, target):
lo, hi = 0, len(a) # half-open range [lo, hi)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < target:
lo = mid + 1 # mid is a "no": answer is right of it
else:
hi = mid # mid is a "yes": answer is mid or left
return lo # lo == hi
def contains(a, target):
i = lower_bound(a, target)
return i < len(a) and a[i] == target
lower_bound([3, 8, 8, 8, 12, 15, 20, 27], 8) # 1Each line of the template has a reason:
histarts atnand not atn − 1, because the answer can benwhen every value is smaller than the target, so the range has to be able to end there.- The middle rounds down, so
lo ≤ mid < hi, andmidis always a valid index inside the range. - A "no" sets
lo = mid + 1, becausemidis ruled out. A "yes" setshi = mid, becausemiditself might be the first "yes". Both moves shrink the range, so the loop always ends.
Each check halves the undecided range, so a search needs about log₂ n checks, which is 20 for a million items. The loop keeps only two indexes.
Variants
Upper bound, last occurrence and counting
The upper bound is the first index whose value is strictly greater than the target, which is the index just after the last copy of the target. It uses the same template with one change: the test a[mid] < target becomes a[mid] <= target. The last occurrence is then upperBound − 1 (after checking that the target exists), and the number of copies is upperBound − lowerBound. Python provides these as bisect.bisect_left and bisect.bisect_right.
// First index i with a[i] > target, or a.length.
function upperBound(a, target) {
let lo = 0, hi = a.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (a[mid] <= target) lo = mid + 1;
else hi = mid;
}
return lo;
}
const a = [3, 8, 8, 8, 12, 15, 20, 27];
upperBound(a, 8) - lowerBound(a, 8); // 3 copies of 8
upperBound(a, 8) - 1; // 3: the last 8
lowerBound(a, 13); // 5: insert 13 here# First index i with a[i] > target, or len(a).
def upper_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
a = [3, 8, 8, 8, 12, 15, 20, 27]
upper_bound(a, 8) - lower_bound(a, 8) # 3 copies of 8
upper_bound(a, 8) - 1 # 3: the last 8
lower_bound(a, 13) # 5: insert 13 hereStopping at the first match
The textbook version returns as soon as a[mid] == target. That is correct when any match will do and the array has no duplicates, or when duplicates do not matter. It is wrong when the question asks for the first or last position, or for a count, because it returns whichever copy the search happens to land on. In the trace above it would return index 2, not index 1.
Rotated sorted arrays
A rotated sorted array, such as [12, 15, 20, 27, 3, 8, 9], is a sorted array whose front part was moved to the back. It is not sorted overall, but at any middle position at least one of the two halves is still sorted. To search it for a target when all values are distinct, compare a[lo] with a[mid] to find the sorted half, check whether the target lies inside that half's value range, and continue in that half if it does or in the other half if not. If the array can contain duplicates, a[lo], a[mid] and a[hi] can all be equal, and then you cannot tell which half is sorted. The only safe move is to shrink the range by one element, so the worst case becomes O(n).
The closed-interval form
Many textbooks write the search with hi = n − 1, the loop condition lo <= hi, and the updates lo = mid + 1 and hi = mid − 1. Here both ends are positions that are still undecided, and the loop stops when the range is empty. It is awkward for first or last occurrences, because mid is discarded even when it might be the answer, so you need extra code to remember the best match seen so far. The half-open template above avoids that, which is why this lesson uses it.
Searching over answers instead of positions
The template does not need an array. It needs a yes or no question whose answers run "no, no, ..., yes, yes" over some range of numbers. For example, "can the job be finished at speed s?" is "no" for slow speeds and "yes" for fast ones, so the smallest working speed is a lower bound over the range of speeds. Binary Search on the Answer covers this in full.
When binary search does not apply
Binary search needs two things: constant-time access to the middle element, and a sorted order or a single "no" to "yes" switch. It does not work on unsorted data, because discarding half of the elements is only safe when order tells you which half is irrelevant. It is a poor fit for a linked list, which has no constant-time access to the middle. For one query on an unsorted array, a linear scan is faster than sorting first, because sorting costs O(n log n).
Pitfalls
In the interview
Several signals in a problem statement point to binary search:
- The input is sorted, or the problem says you may sort it, and the problem asks for a value, a position, or a count of matches.
- The required time is O(log n), or the input is so large that a linear scan is too slow.
- The problem asks for the smallest or largest value that satisfies a condition, and a larger value never makes the condition harder to meet. This is binary search on the answer.
Questions to expect:
- "What if the array contains duplicates and you need the first or last occurrence?" Use the lower bound for the first occurrence and the upper bound minus one for the last, and check that the value there equals the target. Returning at the first match is not enough, because it returns an arbitrary copy.
- "What does your search return when the target is missing?" The lower bound returns the index where the target would be inserted, which can be
n. The caller checksa[i] == targetto tell a hit from a miss. - "Why do you write
lo + (hi − lo) / 2?" The expression(lo + hi) / 2overflows a 32-bit integer when both indexes are near two billion. The other form never exceedshi. - "How do you search a rotated sorted array?" At each step one half around the middle is sorted. Find that half by comparing
a[lo]witha[mid], check whether the target falls inside its range, and keep that half or the other one. This is still O(log n) when the values are distinct. - "What if the rotated array contains duplicates?" When
a[lo],a[mid]anda[hi]are equal, you cannot tell which half is sorted, so you moveloup by one andhidown by one. The average case is still fast, but an array that is almost all one value takes O(n) in the worst case. - "Should the search be recursive or iterative?" Both are O(log n) in time. The iterative version uses O(1) space, while the recursive version uses O(log n) stack space, so the iterative one is the usual choice.
- "How do you search a sorted array whose length you do not know?" Probe indexes 1, 2, 4, 8 and so on until a value is at least the target or the index is past the end, which takes O(log n) probes. Then run a normal binary search inside the last range.
You have a sorted array of timestamps and need to know how many equal a given value. How would you do it?
I would run two binary searches. The lower bound gives the first index that is at least the value, the upper bound gives the first index that is greater than the value, and their difference is the count. Each search is O(log n), so the whole thing is O(log n), against O(n) for a scan.
What does it return if the value is not in the array?
Zero. Both bounds land on the same index, which is where the value would be inserted, so the difference is zero, and I do not need a separate existence check.
And if the array is unsorted?
Then binary search is not valid. For one query I would scan once in O(n). If there are many queries on the same data, I would sort it once for O(n log n), or build a hash map of counts.
What does lowerBound([3, 8, 8, 8, 12, 15, 20, 27], 13) return?
About how many checks does binary search need on a sorted array of 1,000,000 items?
In the template, why does a "yes" set hi = mid and not hi = mid − 1?
You need the number of times 8 appears in a large sorted array. Which approach is correct and fast?
What to practise next
Read Binary Search on the Answer to apply the same template to a range of possible values instead of an array, and Binary Search Trees to see the same halving idea in a tree.