Binary search finds a target in a sorted array by comparing it with the middle element and throwing away the half that cannot contain it. Every comparison halves the search space, so a billion elements need only about 30 steps. More generally, binary search finds the boundary of any monotonic yes/no question, which turns it into a powerful tool for optimization problems far beyond looking things up in arrays.
Think of it like
The higher-or-lower guessing game
I am thinking of a number from 1 to 100. A smart player always guesses the middle: 50, then 25 or 75, and so on. Each "higher" or "lower" answer rules out half of the remaining numbers, so 7 guesses are always enough. Looking up a word in a paper dictionary works the same way: open near the middle, see which side the word falls on, and repeat.
How it works
Maintain a search interval [lo, hi] that is guaranteed to contain the target if it exists. Look at the middle element: if it equals the target you are done; if it is smaller, the target can only be to its right; if it is larger, only to its left. Shrink the interval accordingly and repeat until it is empty.
- 1
Initialize the interval
Set
lo = 0andhi = n - 1. The whole array is the search space. - 2
Probe the middle
Compute
mid = lo + (hi - lo) / 2(rounded down) and comparea[mid]with the target. - 3
Found it?
If
a[mid] == target, returnmid. - 4
Discard half
If
a[mid] < target, setlo = mid + 1. Otherwise sethi = mid - 1. The middle element itself is excluded because it has already been checked. - 5
Stop when empty
When
lo > hithe interval is empty: the target is absent, andlois exactly where it would be inserted.
n = 1,000
10
comparisons at most
n = 1,000,000
20
comparisons at most
n = 1,000,000,000
30
comparisons at most
Every 64-bit integer
64
2⁶⁴ candidates
The overflow-safe midpoint
The textbook midpoint (lo + hi) / 2 has a famous bug: with 32-bit integers, lo + hi overflows once the array has more than about a billion elements, producing a negative index. Joshua Bloch reported in 2006 that this bug had lived in Java's Arrays.binarySearch for about nine years, and the same line appears in countless textbooks.
| Language | Safe midpoint | Why |
|---|---|---|
| Java, C, C++ | lo + (hi - lo) / 2 | hi - lo never exceeds the array length, so nothing overflows |
| Java | (lo + hi) >>> 1 | Unsigned shift treats the overflowed sum as an unsigned 32-bit value, which is correct |
| JavaScript / TypeScript | lo + ((hi - lo) >> 1) or Math.floor((lo + hi) / 2) | Numbers are doubles; avoid (lo + hi) >> 1 on huge values since >> truncates to 32 bits |
| Python | (lo + hi) // 2 | Integers are arbitrary precision, so no overflow is possible |
Invariants and off-by-one errors
The cure for off-by-one errors is to pick an interval convention and write down the invariant it maintains. Every line of the loop then follows from that choice. The two common conventions are the closed interval [lo, hi] and the half-open interval [lo, hi).
Closed [lo, hi]
- Start:
lo = 0,hi = n - 1 - Invariant: if the target exists, it is in
a[lo..hi]inclusive - Loop:
while lo <= hi(one element left is still a candidate) - Shrink:
lo = mid + 1orhi = mid - 1 - Ends with
lo == hi + 1: an empty interval
Half-open [lo, hi)
- Start:
lo = 0,hi = n - Invariant: the answer is in
[lo, hi);hiitself is excluded - Loop:
while lo < hi - Shrink:
lo = mid + 1orhi = mid - Ends with
lo == hi: the answer (possiblyn). Matches C++ iterators and Python slices
Will it terminate?
Every iteration must make the interval strictly smaller. With a rounded-down mid, the update lo = mid is dangerous: when hi = lo + 1, mid equals lo, so lo = mid changes nothing and the loop spins forever. If your logic needs lo = mid, round the midpoint up instead: mid = lo + (hi - lo + 1) / 2.
- 1Choose the interval convention: closed or half-open.
- 2State the invariant: what is true about
loandhiat the top of every iteration? - 3Derive the loop condition: when is the interval empty?
- 4Check that every branch shrinks the interval, including the two-element case.
- 5Decide what to return when the loop ends:
-1,lo, orlo - 1.
Lower bound and upper bound
Instead of asking "where is x?", ask "where does x start?". The lower bound is the first index i with a[i] >= x, and the upper bound is the first index with a[i] > x. Both always exist in the range [0, n], even when x is absent, and together they answer almost every sorted-array question.
Query on [1, 3, 3, 3, 5, 8] | lower_bound | upper_bound | Meaning |
|---|---|---|---|
| x = 3 | 1 | 4 | 3 occurs at indices 1..3; count = 4 − 1 = 3 |
| x = 4 | 4 | 4 | Absent; it would be inserted at index 4 |
| x = 0 | 0 | 0 | Smaller than everything |
| x = 9 | 6 | 6 | Larger than everything: both return n |
The first and last occurrence of a value follow directly. The classic version of this problem asks for both in O(log n) even when the value appears thousands of times, which rules out finding one match and scanning outward (that scan is O(n) in the worst case).
Searching a rotated sorted array
A sorted array rotated at an unknown pivot, such as [4, 5, 6, 7, 0, 1, 2], is no longer sorted, yet binary search still works. The key fact: when you split at mid, at least one half is always sorted. Check whether the target lies inside the sorted half's range; if so, search there, otherwise search the other half.
def search_rotated(a: list[int], target: int) -> int:
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[lo] <= a[mid]: # left half a[lo..mid] is sorted
if a[lo] <= target < a[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half a[mid..hi] is sorted
if a[mid] < target <= a[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
def find_min_rotated(a: list[int]) -> int:
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] > a[hi]:
lo = mid + 1 # the drop (and the minimum) is right of mid
else:
hi = mid # mid itself may be the minimum
return a[lo]Binary search on the answer
Many optimization problems ask for the smallest (or largest) value that satisfies a condition. If the condition is monotonic (once a value works, every larger value also works), you can binary search over the range of possible answers, running a feasibility check at each probe. The total cost is O(C · log R), where C is the cost of one check and R is the size of the answer range.
- 1
Bound the answer
Find a range
[lo, hi]that certainly contains it:lois an obviously too-small value or the smallest legal one,hian obviously feasible one. - 2
Write feasible(x)
A function that answers "can we succeed with value x?", usually a greedy O(n) simulation.
- 3
Prove monotonicity
Argue that
feasible(x)impliesfeasible(x + 1). Without this, binary search gives wrong answers. - 4
Find the first true
Run lower-bound style binary search:
if feasible(mid): hi = mid else: lo = mid + 1.
Koko eating bananas
Koko has piles of bananas and h hours. At speed k she eats from one pile per hour, taking ⌈p / k⌉ hours for a pile of size p. Find the minimum k that finishes within h hours. Faster speeds never take longer, so feasibility is monotonic, and the answer lies in [1, max(piles)].
| Speed k | Hours for piles [3, 6, 7, 11] | Feasible with h = 8? |
|---|---|---|
| 1 | 3 + 6 + 7 + 11 = 27 | No |
| 3 | 1 + 2 + 3 + 4 = 10 | No |
| 4 | 1 + 2 + 2 + 3 = 8 | Yes (the answer) |
| 6 | 1 + 1 + 2 + 2 = 6 | Yes |
| 11 | 1 + 1 + 1 + 1 = 4 | Yes |
Ship packages within D days
Packages with weights w must ship in order within D days, and each day's load cannot exceed the ship's capacity. Find the minimum capacity. The answer lies in [max(w), sum(w)]: below the heaviest package nothing works, and at the total weight one day suffices. To check a capacity, greedily fill each day until the next package would overflow. For weights 1..10 and D = 5, the answer is 15.
def ship_within_days(weights: list[int], days: int) -> int:
def days_needed(cap: int) -> int:
needed, load = 1, 0
for w in weights:
if load + w > cap: # start a new day
needed += 1
load = 0
load += w
return needed
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
if days_needed(mid) <= days:
hi = mid # feasible: try a smaller ship
else:
lo = mid + 1 # too small
return lo| Problem | Answer space | Feasibility check |
|---|---|---|
| Koko Eating Bananas | speed in [1, max(piles)] | Σ ⌈p / k⌉ ≤ h |
| Capacity To Ship Packages | capacity in [max(w), sum(w)] | greedy day count ≤ D |
| Split Array Largest Sum | largest sum in [max(a), sum(a)] | greedy piece count ≤ k |
| Minimum Days to Make m Bouquets | day in [min(bloom), max(bloom)] | bouquets ready by that day ≥ m |
| Magnetic Force Between Two Balls | gap in [1, max − min] | greedy placement fits m balls (find the last true) |
Binary search on real numbers
On a continuous domain there is no mid + 1: you set lo = mid or hi = mid and stop when the interval is small enough. This is the bisection method for finding where a monotonic function crosses a value, for example a square root, an interest rate or the time at which two moving objects meet.
def sqrt(x: float) -> float:
lo, hi = 0.0, max(1.0, x) # sqrt(x) always lies in this range
for _ in range(100): # each iteration halves the interval
mid = (lo + hi) / 2
if mid * mid < x:
lo = mid
else:
hi = mid
return hiExponential search
When the array is unbounded (a stream or an "infinite" sorted list) or the target is probably near the front, first find a range by probing indices 1, 2, 4, 8, … until a[i] >= target, then binary search inside [i/2, i]. If the target sits at position p, this costs O(log p) instead of O(log n). Timsort's galloping mode uses exactly this trick when merging runs where one side keeps winning.
from bisect import bisect_left
def exponential_search(a: list[int], target: int) -> int:
if not a:
return -1
bound = 1
while bound < len(a) and a[bound] < target:
bound *= 2 # 1, 2, 4, 8, ...
lo, hi = bound // 2, min(bound, len(a) - 1) # target index is in [lo, hi]
i = bisect_left(a, target, lo, hi + 1)
return i if i < len(a) and a[i] == target else -1Binary search in standard libraries
| Language | Function | Returns |
|---|---|---|
| Python | bisect.bisect_left(a, x) | Lower bound: first index with a[i] >= x |
| Python | bisect.bisect_right(a, x) | Upper bound: first index with a[i] > x. Both accept key= since Python 3.10 |
| Python | bisect.insort(a, x) | Inserts in order: O(log n) search, but O(n) to shift elements |
| Java | Arrays.binarySearch(a, x), Collections.binarySearch(list, x) | An index of x if found, otherwise -(insertionPoint) - 1 |
| C++ | std::lower_bound, std::upper_bound | Iterators to the lower and upper bound |
| C++ | std::equal_range, std::binary_search, std::partition_point | Both bounds as a pair; a bool; the first element failing a predicate |
| JavaScript / TypeScript | none built in | Write your own; indexOf and includes are linear scans |
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Search (best case) | O(1) | O(1) | Target is at the first midpoint |
| Search (average / worst) | O(log n) | O(1) | At most ⌊log₂ n⌋ + 1 comparisons |
| Recursive search | O(log n) | O(log n) | Call stack depth; prefer the iterative loop |
| Lower / upper bound | O(log n) | O(1) | No early exit: always about log₂ n probes |
| Rotated array search | O(log n) | O(1) | Distinct values; duplicates degrade to O(n) |
| Binary search on the answer | O(C · log R) | O(1) | C = cost of one feasibility check, R = answer range |
| Exponential search | O(log p) | O(1) | p = position of the target; works on unbounded input |
Requires random access and sorted (or monotonic) data. Building that order costs O(n log n) once.
Implementation
Closed interval [lo, hi] with an overflow-safe midpoint. Returns an index of the target or -1.
def binary_search(a: list[int], target: int) -> int:
lo, hi = 0, len(a) - 1 # search the closed range [lo, hi]
while lo <= hi: # non-empty while lo <= hi
mid = lo + (hi - lo) // 2 # safe habit (Python ints cannot overflow)
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1 # target can only be right of mid
else:
hi = mid - 1 # target can only be left of mid
return -1Key takeaways
- Binary search halves a sorted search space each step: O(log n) time, about 30 comparisons for a billion elements.
- Use
lo + (hi - lo) / 2for the midpoint;(lo + hi) / 2overflows in fixed-width integer languages. - Pick closed
[lo, hi]or half-open[lo, hi), state the invariant, and derive the loop condition and updates from it. - Lower bound (first
>= x) and upper bound (first> x) answer insertion points, counts, and first/last occurrence. - Any monotonic yes/no predicate can be binary searched, which is how "binary search on the answer" solves minimize-the-maximum problems.
Common pitfalls
- Mixing interval conventions, such as
hi = nwithwhile lo <= hi(out of bounds) orhi = midwithwhile lo <= hi(infinite loop). - Writing
lo = midwith a rounded-down midpoint, which never shrinks a two-element interval. - Running binary search on unsorted data, or on a predicate that is not actually monotonic, and getting silently wrong answers.
- Finding one match and scanning outward for the first/last occurrence, which is O(n) when the value repeats many times.
- Using an epsilon stopping condition on floating-point bisection that can never be met for large magnitudes.
Interview tips
- Default to the half-open lower-bound template; most variants (first/last occurrence, insertion point, search on the answer) reduce to it.
- When a problem asks for a minimum feasible value and checking one candidate is easy, propose binary search on the answer and justify monotonicity.
- Trace the one-element and two-element cases out loud before declaring the code done.
- Mention the library function you would use in production (
bisect_left,std::lower_bound) after writing your own.
Real-world applications
- Database indexes and B-tree nodes binary search their sorted keys.
git bisectbinary searches commit history for the change that introduced a bug.- Finding thresholds: the smallest machine size, timeout or batch size that meets a target, by testing midpoints.
- Numerical root finding (bisection), and inverting monotonic functions such as cumulative distributions.
Practice problems
Test yourself
Why do careful implementations compute mid = lo + (hi - lo) / 2 instead of (lo + hi) / 2?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.