Binary search & search on the answer
Write bug-free binary search and apply it to monotonic answer spaces.
By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.
In short
Binary search finds a target in a sorted array by repeatedly halving the search range, in O(log n) time. The same idea works on any monotonic yes-or-no condition, such as the smallest speed that finishes a job in time. Clear invariants about what lo and hi mean prevent off-by-one bugs.
Explained simply
Binary search is how you find a word in a paper dictionary. You open it in the middle. If your word comes earlier, you ignore the second half; if later, you ignore the first half. Each look throws away half of what is left.
That halving is very powerful. A sorted list of one million items needs only about 20 looks. A billion items needs about 30. A simple scan from the start could need a billion looks.
Binary search needs one thing: the data must be sorted, or more generally, there must be a yes-or-no question whose answers go "no, no, no, yes, yes, yes" without switching back. You search for the point where the answer flips.
That second idea opens up many problems. "What is the smallest truck capacity that ships all boxes in 5 days?" Bigger capacities always work if smaller ones do. So you can binary search over the capacity itself, even though there is no sorted list in sight.
Binary search is short, but easy to get wrong by one. The trick is to decide exactly what lo and hi mean and keep that promise on every loop.
Press Play on a diagram to walk through it one step at a time.
- 1Range [lo, hi)
Answer lies in this half-open range.
- 2mid
mid = (lo + hi) // 2
- 3Test
a[mid] >= target means hi = mid.
- 4Else
lo = mid + 1
- 5Stop
lo == hi is the answer.
- Back to step 1
- lo = 0, hi = len(a)
- while lo < hi
- hi = mid or lo = mid + 1
- Returns an insertion point
- lo = 0, hi = len(a) - 1
- while lo <= hi
- hi = mid - 1 or lo = mid + 1
- Returns index or -1
In depth
Invariants that prevent off-by-one bugs
Pick one convention and never mix it. The half-open style keeps the answer in [lo, hi): lo is a possible answer, hi is one past the last possible answer. Start with lo = 0, hi = len(a). Loop while lo < hi. Compute mid = (lo + hi) // 2, which is always strictly less than hi. If mid could be the answer, set hi = mid; otherwise set lo = mid + 1. Each step shrinks the range, and the loop ends with lo == hi, the answer.
The closed style keeps the answer in [lo, hi] with hi = len(a) - 1, loops while lo <= hi, and uses hi = mid - 1 or lo = mid + 1. It suits "find exact match or return -1".
The classic infinite loop: using lo = mid together with mid = (lo + hi) // 2. When hi = lo + 1, mid equals lo and nothing changes. If you need lo = mid, round up: mid = (lo + hi + 1) // 2.
- [lo, hi): while lo < hi, hi = mid or lo = mid + 1
- [lo, hi]: while lo <= hi, hi = mid - 1 or lo = mid + 1
- lo = mid needs mid rounded up
First and last occurrence with bisect
In a sorted list with duplicates, lower bound is the first index i with a[i] >= x. Upper bound is the first index with a[i] > x. The occurrences of x fill exactly the range [lower, upper), so the count is upper - lower, found in O(log n).
Python's bisect module provides these: bisect_left(a, x) is the lower bound and bisect_right(a, x) (also called bisect) is the upper bound. To test membership: i = bisect_left(a, x); found = i < len(a) and a[i] == x. Last occurrence is bisect_right(a, x) - 1 if that index holds x.
insort_left and insort_right insert while keeping the list sorted: O(log n) to find the spot but O(n) to shift elements. Since Python 3.10, all bisect functions take a key= argument, applied to the list items (not to x), so x must already be a key value.
- count of x = bisect_right(a, x) - bisect_left(a, x)
- Largest item < x: a[bisect_left(a, x) - 1]
- key= on bisect functions needs Python 3.10+
- Step 1bisect_left
Returns 1: first index with a[i] >= 3.
- Step 2bisect_right
Returns 4: first index with a[i] > 3.
- Step 3Range [1, 4)
All the 3s.
- Step 4Count
4 - 1 = 3 copies.
Searching a rotated sorted array
A sorted array rotated at some pivot looks like [4, 5, 6, 7, 0, 1, 2]. It is not sorted, but one fact rescues binary search: for any mid, at least one of the two halves [lo, mid] or [mid, hi] is sorted.
With distinct values and the closed convention: if a[lo] <= a[mid], the left half is sorted. Then the target is in the left half exactly when a[lo] <= target < a[mid]; otherwise go right. If instead the right half is sorted, the target is there exactly when a[mid] < target <= a[hi]. Each step still halves the range, so it is O(log n).
To find the rotation point (the minimum), compare a[mid] with a[hi]: if a[mid] > a[hi], the minimum is to the right of mid; otherwise it is at mid or to the left. With duplicates, a case like a[mid] == a[hi] gives no information, so you can only drop hi by one, and the worst case becomes O(n).
Binary search on the answer
Many optimisation problems have the shape: find the smallest value v such that feasible(v) is true, where feasible is monotonic (once true, true for all bigger v). Then binary search over v instead of over an array.
The recipe: find a range [lo, hi] that surely contains the answer. Write feasible(v), usually a greedy O(n) check. Run the half-open lower-bound loop: if feasible(mid), hi = mid, else lo = mid + 1. Total time is O(n log R) where R is the range size.
Example: ship packages in order within D days; find the minimum ship capacity. lo = max(weights) (one package must fit), hi = sum(weights) (one day). feasible(c) loads packages greedily day by day and counts days needed. Other examples: Koko eating bananas, splitting an array into k parts to minimise the largest sum, or the square root of an integer. For real-valued answers, loop a fixed number of times (say 100) instead of comparing floats.
- 1Range
lo = max(w), hi = sum(w)
- 2Try mid
Simulate days needed with capacity mid.
- 3Fits in D days
hi = mid (maybe smaller works).
- 4Too many days
lo = mid + 1
- 5lo == hi
Minimum capacity found.
Real-world details
In languages with fixed-size integers, (lo + hi) / 2 can overflow when lo and hi are large. A famous case was Java's Arrays.binarySearch, which carried this bug for years until it was fixed in 2006. Writing lo + (hi - lo) / 2 avoids it. Python integers never overflow, so (lo + hi) // 2 is safe.
Binary search makes at most floor(log2 n) + 1 probes for an exact-match search: 20 for one million items. But each probe jumps around memory, so for small arrays (under roughly 100 items) a linear scan can be just as fast in compiled languages.
Binary search appears in many tools. git bisect finds the commit that introduced a bug by testing the middle commit and halving. Databases use B-tree indexes, which are a many-way generalisation. And sorted arrays plus bisect make a simple, memory-light alternative to a balanced tree when updates are rare.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Write binary search with clear invariants~40m
- 2Find first and last occurrence~40m
- 3Search a rotated sorted array~40m
- 4Binary search on the answer space~40m
- 5Use the bisect module~40m
Key points
- O(log n) time and O(1) space iteratively.
- Search on the answer: binary search over values when feasibility is monotonic.
- bisect_left and bisect_right give first and one-past-last positions.
- Rotated sorted arrays: one half is always sorted, so check which.
Key terms
Tap a card to flip it. 0/4 known
Examples
def lower_bound(a, target): # O(log n)
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] >= target: hi = mid
else: lo = mid + 1
return lo
def min_speed(piles, hours): # search on the answer
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if sum(-(-p // mid) for p in piles) <= hours: hi = mid
else: lo = mid + 1
return loSearch in a rotated sorted array
Search [4, 5, 6, 7, 0, 1, 2] for 0. lo = 0, hi = 6, mid = 3 (value 7). The left half [4..7] is sorted, but 0 is not in [4, 7), so go right: lo = 4. mid = 5 (value 1). a[4] = 0 <= 1, so the left half [0, 1] is sorted and 0 is in [0, 1): hi = 4. mid = 4, value 0: found at index 4.
def search_rotated(a, target):
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 sorted
if a[lo] <= target < a[mid]: hi = mid - 1
else: lo = mid + 1
else: # right half sorted
if a[mid] < target <= a[hi]: lo = mid + 1
else: hi = mid - 1
return -1
print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0)) # 4Minimum ship capacity within D days
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], D = 5. The answer lies between 10 (the heaviest package) and 55 (everything in one day). The check fills each day greedily and starts a new day when the next package would not fit. Capacity 15 works: [1..5], [6, 7], [8], [9], [10] is 5 days. Capacity 14 needs 6 days. So the answer is 15, found with about log2(46), about 6, checks of O(n) each.
def ship_within_days(w, days):
def days_needed(cap):
d, load = 1, 0
for x in w:
if load + x > cap:
d, load = d + 1, 0
load += x
return d
lo, hi = max(w), sum(w)
while lo < hi:
mid = (lo + hi) // 2
if days_needed(mid) <= days: hi = mid
else: lo = mid + 1
return lo
print(ship_within_days([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)) # 15Quick reference
- Worst case floor(log2 n) + 1 probes: 20 for 10^6, 30 for 10^9
- Half-open: lo, hi = 0, len(a); while lo < hi; hi = mid or lo = mid + 1
- bisect_left: first i with a[i] >= x; bisect_right: first i with a[i] > x
- Count of x in sorted a: bisect_right(a, x) - bisect_left(a, x)
- If you write lo = mid, use mid = (lo + hi + 1) // 2 to avoid an infinite loop
- Search on answer: monotonic feasible(v), cost O(check x log range)
- Rotated array: one half is always sorted; with duplicates worst case is O(n)
Common mistakes
- Mixing closed and half-open conventions, causing infinite loops.
- Applying binary search to unsorted data or a non-monotonic condition.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write search_range(a, x) that returns [first, last] indexes of x in a sorted list, or [-1, -1], in O(log n) using bisect. Example: ([5, 7, 7, 8, 8, 10], 8) gives [3, 4].
- Exercise 2medium
Write isqrt(n) that returns the largest integer r with r * r <= n using binary search, without math functions. Example: isqrt(26) is 5, isqrt(0) is 0.
- Exercise 3hard
Write find_min_rotated(a) that returns the minimum of a rotated sorted array of distinct values in O(log n). Example: [4, 5, 6, 7, 0, 1, 2] gives 0, [1, 2, 3] gives 1.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does binary search work on linked lists?
- Not efficiently. Reaching the middle of a linked list takes O(n) steps, so the whole search is O(n). Use an array, a balanced tree or a skip list instead.
- Should I use bisect or write my own binary search?
- Use bisect for sorted lists: it is implemented in C, tested and clear. Write your own when searching over an answer range or a custom condition.
- Is it worth sorting just to binary search once?
- No. Sorting costs O(n log n), more than a single O(n) linear scan. Sort once when you will make many searches on the same data.