Skip to content
Technique

When to use binary search on the answer

Binary search on the answer works when the result is a number in a known range and a yes/no check of any guess is monotonic. Here is how to recognise it, set the bounds, and avoid the off-by-one traps.

Use binary search on the answer when the answer is a number in a known range, a yes/no check of any guess is cheap to compute, and that check is monotonic: once a guess works, every larger one works too. You then search the range of guesses instead of an array.

Most people meet binary search as a way to find a value in a sorted array. That version is a special case, and it hides the real idea. The real idea is that you can binary search anything that has a single flip point from "no" to "yes". Once you see that, a whole family of problems that look like optimisation puzzles collapse into a short loop wrapped around a greedy check. This essay covers how to recognise those problems, how to prove the check is monotonic, how to set the bounds, and where the technique quietly goes wrong.

What does binary search on the answer actually mean?

It means you stop asking "what is the best value?" and start asking "is this particular value good enough?", then use the answers to narrow down a range. The sorted array disappears; the thing being searched is the space of possible answers.

Here is the framing I use. Imagine hiring a contractor to renovate a kitchen. You cannot ask, "What is the lowest price you could possibly do this for?" because a contractor will not tell you that honestly, and you have no way to compute it yourself. But you can ask, "Would you do it for 12,000?" and get a straight yes or no. If the answer is yes for 12,000, it is also yes for 13,000, because anyone willing to do the job for less will do it for more. If it is no for 12,000, it is no for 11,000. Each question halves the range of prices still in play, and after a handful of questions you have the lowest price that gets a yes. The contractor is your feasibility function. The price is your answer. The only requirement is that the yes/no responses form a clean step: all no, then all yes, with exactly one switch.

Formally, you need three things:

  • A bounded integer (or real) answer space. A lower bound and an upper bound that you can compute before the search starts.
  • A feasibility function ok(x) that returns true or false for a candidate answer, and runs in something like linear time.
  • Monotonicity. If ok(x) is true then ok(x+1) is true (for a minimisation problem), or the mirror image for a maximisation problem.

When all three hold, the loop is the same every time, and the cost is the cost of one check multiplied by the number of halvings of the range. If you want the general reference version, the page on binary search on the answer lays out the template. The rest of this essay is about the judgement that the template does not give you.

How do you know a problem can use binary search on the answer?

Look for a request to minimise a maximum or maximise a minimum, where the quantity is a single number and you can test a proposed value with one greedy pass. Those phrases are the strongest signal there is.

Some wording patterns that reliably point to this technique:

  • "Minimise the largest sum / load / time / distance." Splitting an array into groups, shipping packages within a number of days, scheduling jobs across workers.
  • "Maximise the smallest gap." Placing k items on a line so that the closest pair is as far apart as possible.
  • "Find the smallest speed / capacity / size that still finishes in time." Eating piles of food within a deadline, printing with a minimum rate.
  • "Find the k-th smallest value" in a structure you cannot sort cheaply, such as a multiplication table or a matrix of pairwise differences.

The deeper test is the monotonicity proof, and it is worth doing in words, every time, before writing code. Ask: if this value works, why must a slightly easier value also work? For "largest piece sum at most L", the argument is that any split that keeps every piece under L also keeps every piece under L+1. That is true by definition of "at most". The check is monotonic because the condition is a threshold, not an equality.

Here is a case where the proof fails. Suppose a problem asks whether some subset of numbers sums to exactly s. You cannot binary search on s: a subset might hit 10 and 12 but not 11. Feasibility is not a step, it is a scatter. The same trap appears in any "exactly k" formulation. I have seen candidates reach for binary search because the problem has a range and the word "minimum", without ever asking whether the yes/no function is a step. If you cannot argue monotonicity in one sentence, do not write the loop.

A related check is the one from the sorted-array world. If the problem is about finding a position in a rotated array, that is a different flavour, covered in search in rotated sorted array, where the monotonic property lives in the data. Here it lives in the answer space.

What does a worked example look like with real numbers?

Take this problem, restated in my own words: you have an array of positive integers and a number k. You must cut the array into exactly k contiguous pieces, and you want the largest piece sum to be as small as possible. For [7, 2, 5, 10, 8] with k = 2, what is that smallest possible largest sum?

The direct approach is dynamic programming over (prefix length, pieces used), which costs about n squared times k. For a list of 1,000 numbers and k = 50, that is roughly 50 million steps, fine. For 100,000 numbers it is hopeless. The binary search version does not care how the splits are arranged. It asks: "If no piece may exceed L, how many pieces do I need?" A greedy sweep answers that: keep adding numbers to the current piece until the next one would push it over L, then start a new piece. If the count is at most k, then L is feasible.

Bounds first. No piece can be smaller than the largest single element, so the answer is at least 10. No answer needs to exceed the total, 32, which corresponds to one piece. The search range is [10, 32], which is 23 candidate values. Since log base 2 of 23 is about 4.5, I expect four or five probes.

def min_largest_sum(nums, k):
    def pieces_needed(limit):
        count, running = 1, 0
        for x in nums:
            if running + x > limit:
                count += 1
                running = x
            else:
                running += x
        return count

    lo, hi = max(nums), sum(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if pieces_needed(mid) <= k:
            hi = mid
        else:
            lo = mid + 1
    return lo

Trace it by hand. With lo = 10, hi = 32, mid = 21: the sweep gives pieces [7,2,5] (14; adding 10 would make 24), then [10,8] (18). Two pieces, which is within k, so hi becomes 21. Next, mid = 15: [7,2,5] is 14, then 10 starts a new piece, 10 plus 8 is 18 which is over 15, so 8 starts a third piece. Three pieces is too many, so lo becomes 16. Next, mid = 18: [7,2,5], then [10,8] exactly 18, two pieces, so hi becomes 18. Next, mid = 17: [7,2,5], [10], [8], three pieces, so lo becomes 18. The range has collapsed to 18, and that is the answer. Four probes (21, 15, 18, 17), matching the estimate.

Now scale it. Suppose n is 100,000 and each value is at most 10,000. The total is at most 109, so the range holds up to a billion values, and log base 2 of that is about 30. Each probe is one pass of 100,000 steps, so the whole search costs about 3 million basic operations. That runs in well under a second even in Python, while the DP at n squared times k is roughly 1010 times k and does not finish at all. The speedup does not come from cleverness in the search; it comes from replacing an optimisation over arrangements with a decision over a single number.

How do you choose the bounds and avoid off-by-one errors?

Choose bounds so that the true answer is always inside the range, then pick the loop form that matches your direction: mid = (lo + hi) // 2 with hi = mid when minimising, and mid = (lo + hi + 1) // 2 with lo = mid when maximising.

Bounds are the quiet half of the technique, and getting them slightly wrong gives answers that are wrong by one on exactly the tests you did not run. The lower bound should be the smallest value that could possibly be the answer, not zero by default. In the splitting example, using lo = 0 still works, because ok(0) is false and the search moves up, but it adds a few wasted probes and, in other problems, can cause division by zero inside the check. The upper bound should be a value that is guaranteed feasible. If you are unsure, use something generous, because each doubling of the range costs only one extra probe. A range of 109 takes 30 probes; a range of 1018 takes 60. Over-wide bounds are cheap. Too-narrow bounds are wrong.

The loop shape matters more than most people admit. In a minimisation, you are looking for the first true, so when ok(mid) is true you keep mid with hi = mid, and when it is false you discard it with lo = mid + 1. The loop condition is lo < hi, and when it ends, lo equals hi is the answer. In a maximisation, you are looking for the last true. If you write mid = (lo + hi) // 2 and then lo = mid, then with lo = 4 and hi = 5, mid is 4, lo stays 4, and the loop never terminates. Rounding the midpoint up fixes it. This asymmetry is the most common source of infinite loops, and it is the same family of trouble discussed in why binary search is so hard to get right.

For real-valued answers, such as minimising the maximum distance between stations, there is no off-by-one, but there is a precision question. Instead of looping until lo equals hi, loop a fixed number of times, say 60 to 100 iterations, which shrinks the range by a factor of 260. A fixed count is more robust than comparing floats to a tolerance.

How does it compare with other ways to solve the same problem?

It beats a linear scan of candidate answers by a factor of the range size over its logarithm, and it beats dynamic programming when the DP state is large, but it only applies when the monotonic check exists.

ApproachTime for the split exampleSpaceRequiresMain risk
Try every limit from max to sumO(n * range), up to 105 * 109O(1)Nothing specialFar too slow at scale
Binary search on the answerO(n log range), about 3 * 106O(1)Monotonic greedy checkWrong bounds or loop form
Dynamic programming over (index, pieces)O(n2 * k)O(n * k)Optimal substructureToo slow for large n
Brute-force all cut positionsO(C(n-1, k-1))O(k)NothingExponential blowup

The table shows why this technique is so valuable in interviews. It sits in the sweet spot: linear check, logarithmic outer loop, no extra memory. It also shows its limit. The first row is exactly what the second row optimises, and the only thing that makes the optimisation legal is monotonicity. Without it you fall back to the DP, where the discussion in how to optimize a brute force solution applies.

What mistakes do people make with this technique?

The three big ones are skipping the monotonicity argument, writing a feasibility check that is itself wrong, and using a loop form that does not match the direction of the search.

The feasibility check deserves the most suspicion, because the outer loop is mechanical and the check is where the problem lives. In the splitting example the greedy is correct because packing as much as possible into each piece never hurts: any other split with the same limit needs at least as many pieces. If you cannot make that exchange argument, the greedy might undercount pieces and the binary search will faithfully converge on a wrong answer. A good habit is to test the check alone first. Write pieces_needed, call it with a few limits on small inputs, and confirm by hand that the counts go down as the limit goes up, never up again. That one sanity pass catches a surprising number of bugs.

A second mistake is forgetting that the check must be monotonic in the direction you assumed. Beginners sometimes write if ok(mid): lo = mid + 1 in a minimisation because the sample answer looked like it should move up. Say the direction out loud: "if mid works, can the answer be smaller? Yes, so I keep mid and shrink hi."

A third mistake is cost accounting. People see "binary search" and write O(log n), forgetting that the log is over the size of the answer range, not over the input length, and that every probe costs a full pass. The honest complexity is O(n log R), where R is the width of the range. If R is 109 and n is 105, that is about 3 million, which is excellent. If the check itself is quadratic, you have 30 times a quadratic, and the technique may not save you. State the formula and plug in the numbers before committing to it.

The last mistake is overusing it. When the answer is directly computable, say a maximum or a sum, a search is wasted effort. The technique earns its place only when the answer is easy to verify and hard to construct. That asymmetry between checking and building is the heart of it, and once you start noticing it, you will find it in problems well beyond arrays: capacity planning, rate limiting thresholds, even choosing a batch size so that a job fits in memory.

Frequently asked questions

Does the array have to be sorted for binary search on the answer?

No. The input can be in any order, because you are not searching the input. You are searching the range of possible answers, and the requirement is that the yes/no feasibility check is monotonic over that range.

What is the time complexity of binary search on the answer?

It is O(C log R), where C is the cost of one feasibility check and R is the width of the answer range. For a linear check over n elements and a range up to 109, that is about 30 passes, or roughly 30n operations.

How do I decide between this and dynamic programming?

Try to write a monotonic yes/no check with a greedy argument first. If one exists, binary search is usually simpler and much faster. If the check needs to remember choices from earlier decisions, or feasibility is not a clean threshold, use dynamic programming instead.

If you want the template in its barest form to practise against, start with the binary search on the answer concept page, and write the monotonicity argument in a single sentence before you write any code.