Lesson 8: Binary Search on the Answer
Binary search is usually taught as a way to find an item in a sorted list. But the deeper idea is more general: whenever you can test a candidate answer with a yes-or-no question, and the answers are ordered — all the noes come before all the yeses, or the other way round — you can binary search the answer itself. This technique, called binary search on the answer, turns many hard-looking problems into easy ones, and it is a favourite of contest setters.
Here is the classic example. You have a row of books with given page counts, and you must split them into a fixed number of groups, keeping the books in order, so that the largest group total is as small as possible. Trying every split is far too slow. But suppose someone asks: can you do it with every group totalling at most 100 pages? That question is easy to answer — walk along the books, filling groups greedily, and count how many groups you need. And the answer is monotonic: if 100 pages is enough, then 101 is enough too; if 99 is not enough, then 98 is not either. So the feasible limits form a sorted line of noes followed by yeses, and binary search finds the smallest feasible limit.
def groups_needed(pages, limit):
groups, current = 1, 0
for p in pages:
if p > limit:
return float("inf") # one book alone breaks the limit
if current + p > limit:
groups += 1
current = p
else:
current += p
return groups
def smallest_max_group(pages, k):
lo, hi = max(pages), sum(pages)
while lo < hi:
mid = (lo + hi) // 2
if groups_needed(pages, mid) <= k:
hi = mid
else:
lo = mid + 1
return lo
print(smallest_max_group([100, 200, 300, 400, 500], 3)) # 600
The pattern: a monotonic check
Every binary-search-on-the-answer problem has the same shape. First, find the range of possible answers — here, from the biggest single book to the sum of all pages. Second, write a check(x) function that answers yes or no for a candidate x, and make sure it is monotonic: once it says yes, it says yes for every larger value. Third, binary search for the boundary between no and yes. The check function is usually the easy part — a greedy scan or a simple count — and the binary search does the heavy lifting of finding the optimum.
The common mistakes are all about boundaries. The low end must be feasible or infeasible in a known way, the high end must be feasible, and the loop must end with lo pointing at the first feasible value. A useful discipline is to test the check function on its own first, with small numbers, before wrapping it in a search. When you can state the monotonic property in one sentence — "if a limit of X works, any larger limit works too" — you have understood the problem, and the code almost writes itself.
Going further
Binary search on the answer appears in many disguises. One common form is minimising the maximum time to finish a set of tasks: given workers who each take a certain time per task, what is the smallest time limit in which all tasks can be done? The check function counts how many tasks can be completed within a candidate limit, and the answer is monotonic — a larger limit can only help. Another form is finding the smallest capacity that lets a ship carry all packages within a given number of days. Once you have seen the pattern twice, you will start spotting it everywhere.
The same idea works with real numbers, not just integers. To find a square root, or the point where a function crosses zero, you can binary search over a continuous range, repeating until the interval is smaller than the precision you need. The loop condition changes — instead of lo < hi you repeat a fixed number of times, such as a hundred iterations, which is enough to shrink any reasonable interval to far more precision than a floating-point number can hold. The monotonic property is what matters, not whether the answers are whole numbers.
To practise the pattern, try inventing a check function for a problem of your own: you have to print a book of n pages, and each day you can print at most k pages — what is the smallest number of days? The check function is trivial: can it be done in d days, which is true when d * k >= n. The answer is monotonic in d, so binary search finds the smallest feasible d. The problem is too easy to need binary search — simple division gives the answer — but the exercise is about recognising the shape: a yes-or-no question, a monotonic answer, and a boundary to find. Once the shape is familiar, you will spot it in problems where the check function is the hard part.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Algorithms and Data Structures Tutorial - Full Course for Beginners — freeCodeCamp.org
Pasan Premaratne and Jay McGavren's full course ends with a deep dive into sorting and searching — the same ground as this unit, with code you can follow along.
Key Terms
- Binary search on the answer
- Binary searching over possible answers, using a yes/no check function, instead of searching a list.
- Monotonic
- A property that only changes once: all noes, then all yeses (or the reverse).
- Check function
- A function that tests whether a candidate answer is feasible, returning yes or no.
- Feasible
- A candidate answer that satisfies the problem's constraints.
- Greedy scan
- A single pass that builds groups (or a solution) by taking the best immediate choice at each step.
- Lower bound (lo)
- The smallest candidate answer to consider; the search narrows it upward.
- Upper bound (hi)
- The largest candidate answer to consider; known to be feasible.
Discussion Questions
- Why must the check function be monotonic for binary search on the answer to work? What goes wrong if yes and no answers are mixed up?
- In the book example, why is the smallest possible answer the biggest single book, and the largest the sum of all pages?
- Think of another problem where you could binary search the answer — for example, the minimum time to finish a set of tasks. What would your check function test?
Practice Questions
- What makes binary search on the answer possible?
- In the example, what does
groups_needed(pages, 100)return for [100, 200, 300, 400, 500]? - Why does the search start with
lo = max(pages)? - What is the answer for [100, 200, 300, 400, 500] with k = 3, and what grouping achieves it?
- Why is the check function usually a greedy scan?
Show answers
- A monotonic yes/no check function over an ordered range of candidate answers. Once the check flips from no to yes, it never flips back, so the boundary can be found by halving.
- Infinity — it returns float("inf"). The book of 200 pages alone exceeds the limit of 100, so no grouping can work.
- No limit smaller than the biggest book can ever work. A group must hold at least its largest book, so smaller limits are certainly infeasible.
- 600, achieved by [100, 200, 300], [400], [500]. The group totals are 600, 400 and 500, so the largest is 600; with a limit of 599 the greedy scan needs 4 groups, so 599 is infeasible.
- Because testing a candidate limit only needs one pass with the best immediate choice. Filling each group as full as possible minimises the number of groups, which is exactly what the check needs.