Recognition guide
Binary search beyond sorted arrays: searching the answer
Most people first meet binary search as "find a value in a sorted array". The idea is wider than that. Binary search works whenever you can ask a yes-or-no question about a candidate and the answers flip from one to the other exactly once. The candidates do not have to be array elements. They can be speeds, capacities, days, or distances.
This guide is about spotting those problems. It does not re-teach the basic search. For that, read the Binary Search pattern page. Here you learn the wording that says "search the answer" before you start on a loop.
The one-sentence test
Ask whether you could check a guess quickly, and whether a bigger guess can only help (or only hurt).
- If "can I do it with value x?" is easy to answer, and
- if every x on one side of some boundary says yes and every x on the other side says no,
then the answer is that boundary, and binary search finds it in O(log of the range) checks.
Signals that point to searching the answer
These phrases describe a boundary between "works" and "does not work".
- "Minimum possible maximum" or "maximize the minimum". Splitting work into groups so the biggest group is as small as possible is the classic shape.
- "Smallest x such that", "largest x such that". The statement names the boundary directly.
- "At most k days / workers / groups / trips." A larger capacity or speed never makes it harder to fit within k.
- "Minimum speed, capacity, or time to finish." More of the resource can only help.
- A big range of candidates with a cheap check. If the answer could be anywhere from 1 to a billion, and one check is a single pass, the range is the thing to halve.
Signals from the constraints
Constraints often give it away before the wording does.
- The answer range is huge, but the input is modest. Values up to a billion with a list of a hundred thousand items suggests O(n log range).
- The statement asks for a number, not a list. You return the capacity, not the arrangement that achieves it.
- A greedy check is easy. If you can walk the input once and decide "yes, it fits", the check is your predicate.
Counter-signals
These look like a reason to search the answer and are not.
- No monotonic property. If a guess of 5 works, 6 fails, and 7 works again, there is no single boundary. Binary search will return a wrong answer without telling you.
- An unsorted lookup. "Find this value" in an unsorted list is not a boundary problem. Use a hash map.
- "All" or "every" match. Binary search finds one boundary. If you need every position that matches, find the boundary and then walk, or use another pattern.
- A check that costs as much as the original problem. If each guess needs a full search of its own, the total cost may not be worth it.
- Small ranges. If the candidates run from 1 to 20, a plain loop over them is simpler and fast enough.
The decision checklist
- Can you write a function
works(x)that returns yes or no for one candidate? - Is
worksmonotonic? Reason about it: if x works, does every larger (or smaller) x also work? - Do you know the smallest and largest sensible candidates? The low end is often the largest single item. The high end is often the sum of everything.
- Do you want the first yes or the last yes? Decide before you write the loop.
- Is one check cheap enough? Total cost is the cost of one check times the number of halvings.
The first-yes template
This version finds the smallest candidate for which works is true. Only the check changes between problems.
function firstWorking(low: number, high: number, works: (x: number) => boolean): number {// Invariant: the answer is in [low, high]; works(high) is true.while (low < high) {const mid = low + Math.floor((high - low) / 2);if (works(mid)) {high = mid; // mid might be the answer, so keep it} else {low = mid + 1; // mid fails, so everything below it fails too}}return low;}
low + (high - low) / 2 avoids overflow in languages with fixed-size integers.Three worked examples
1. "There are piles of items and h hours. Each hour you can eat up to k items from one pile. Return the smallest k that finishes everything within h hours."
Clues: "smallest k" and "within h hours". A faster speed never takes more hours. Candidates run from 1 to the largest pile. The check adds up the hours each pile needs at speed k and compares the total to h.
Pattern: binary search on the answer.
2. "Packages must ship in order within d days. Return the smallest ship capacity that makes it."
Clues: "smallest capacity" and "within d days". A bigger ship never needs more days. Candidates run from the heaviest package to the sum of all packages. The check loads packages greedily and counts the days.
Pattern: binary search on the answer.
3. "Return the integer square root of n, rounded down."
Clues: "largest x such that". The statement
x * x <= nis true up to a boundary and false after it. Here you want the last yes, so search for the first x wherex * x > nand subtract one.Pattern: binary search on the answer, with no array at all.
Common traps
- A check that is not monotonic. Test the idea on a small case by hand. If larger guesses can fail after smaller ones pass, stop.
- Wrong bounds. If the low end is below the largest single item, the check may return nonsense for guesses that cannot hold even one item.
- Mixing up first-yes and last-yes. Say which you want before you write the loop. For the last yes, search for the first no and subtract one.
- Shrinking the wrong way. With
low < high, settinghigh = mid - 1after a yes can throw the answer away, becausemiditself might be it. Keepmidon a yes. Pairinglow = midwith a rounded-downmidcan loop forever, so movelowtomid + 1on a no. - Rounding in the check. Hours per pile is a ceiling, not a floor. A pile of 7 at speed 3 takes 3 hours, not 2.
Quick answers
Does the array have to be sorted?
Not when you search the answer. There is no array to sort. What must be ordered is the yes-or-no outcome across the candidates.
How do I know the check is monotonic?
Argue it in one sentence: "a bigger capacity can only reduce the days". If you cannot say that sentence honestly, the problem is not a fit.
What does it cost?
One check, O(n) for a single pass, times about log of the range. A range of a billion takes about 30 checks.
Practice it on Algofily
Recognizing the pattern is a skill on its own, so Algofily trains it before you write code. Each problem moves through seven stages: Understand, Pattern, Think, Code, Tests, Debug, and Explain. In the Code stage, Algofily AI can give progressive hints (sign-in required).
- Read the Binary Search pattern page for the sorted-list walk-through, the insert index, searching the answer, and the problems that practice it.
While you code, Algofily AI can ask a question and open the next hint.