Binary Search on the Answer
Binary search over the range of possible answers using a monotonic feasibility check: a very common pattern in product-company OAs.
Intermediate · about 6 hours · difficulty 4/5
Learn first: Binary Search on Arrays
Many optimisation problems say "find the minimum maximum" or "the smallest value such that...". If you can check whether a candidate answer x is feasible, and feasibility is monotonic (if x works, every larger x works), binary search on x.
The recipe
- Find the answer range [lo, hi], for example 1 to max(arr) or 1 to sum(arr).
- Write
feasible(x), usually a greedy O(n) pass. - Binary search for the smallest feasible x. Total cost: O(n log(range)).
Classic problems
Koko Eating Bananas, Capacity To Ship Packages Within D Days, Split Array Largest Sum, Book Allocation (GfG), Aggressive Cows (SPOJ), Minimum Number of Days to Make m Bouquets, Find the Smallest Divisor Given a Threshold, Magnetic Force Between Two Balls, Painter's Partition, Nth root of a number.
Spotting it
- Phrases like "minimise the maximum", "maximise the minimum", "least capacity", "at least k".
- Large answer ranges (up to 1e9 or 1e18) with n up to 1e5.
- Binary search on real numbers: loop a fixed 100 times instead of comparing with an epsilon.
Pitfalls
- Getting the feasibility direction backwards, so the search converges to the wrong end.
- Overflow inside feasible() when summing; use 64-bit integers.
- Setting lo too high (for example max(arr) in a problem where the answer can be smaller).
You are ready to move on when you can explain why Aggressive Cows is "maximise the minimum distance" and write its feasibility check in five lines.
Key concepts
- Monotonic feasibility
- Choosing the search range
- Greedy feasibility checks
- Minimise the maximum
- Maximise the minimum
- Binary search on real numbers
Mini project
Solve these 10 in 7 days, log time and pattern: Sqrt(x), Koko Eating Bananas, Find the Smallest Divisor Given a Threshold, Capacity To Ship Packages Within D Days, Minimum Number of Days to Make m Bouquets, Aggressive Cows, Book Allocation, Split Array Largest Sum, Magnetic Force Between Two Balls, Kth Missing Positive Number.
Check yourself
Why is feasibility monotonic in Capacity To Ship Packages, and what are the correct lo and hi?
Free resources
- USACO Guide: Binary Search (USACO Guide)
- Codeforces EDU: Binary Search (Codeforces)
- takeUforward (takeUforward)