Binary Search on the Answer

How to binary search over the possible answers instead of an array, how to recognise these problems, and what interviewers ask about them.

16 minLesson 7 of 7
On this page
  1. How binary search on the answer works
  2. Worked example: the smallest daily limit
  3. Code
  4. Time and space cost
  5. Variants
  6. Pitfalls
  7. In the interview
  8. What to practise next

Binary search on the answer is used for problems that ask for the smallest or largest value satisfying some condition, when checking whether one particular value satisfies the condition is easy. Instead of searching an array, you search the range of possible answers, and the check takes the place of the comparison with a[mid]. It reduces a problem that seems to need every possibility to be tried to about log₂ of the range size checks.

Without it, you would try the candidate answers one at a time from the smallest upward, and each try costs a full check. When the answer can be anywhere up to a billion, that is far too slow, while binary search needs about 30 checks.

How binary search on the answer works

The technique applies when the candidate answers can be split into a block of "no" values followed by a block of "yes" values, where "yes" means the candidate satisfies the condition. If a candidate works, every larger candidate must work as well. This is called being monotone. The answer you want is then the first "yes", and finding the first "yes" in a sorted run of no and yes is exactly the lower-bound search from Binary Search. The positions are candidate answers instead of array indexes, and the comparison is a function call instead of a read from the array.

To use it you need three things:

  1. Bounds. A lo that is the smallest candidate worth considering, and a hi that is certain to be a "yes".
  2. A fast check. A function that takes a candidate and returns yes or no, usually with one greedy pass over the input.
  3. Monotonicity. A reason why a "yes" for x implies a "yes" for x + 1. You should be able to state this reason in one sentence before you write any code.

Worked example: the smallest daily limit

You have six podcast episodes to listen to in order, of 40, 25, 60, 30, 45 and 20 minutes. You listen to whole episodes only and want to finish in at most 3 days. What is the smallest daily listening limit that makes this possible?

Checking a limit is easy. Fill each day with episodes until the next one would go over the limit, then start a new day, and count the days. With a limit of 80 this gives 40 + 25, then 60, then 30 + 45, then 20, which is 4 days, so 80 is too small. Filling each day as far as possible is correct because it never leaves a later day with more work than any other way of splitting the list would.

The candidates are monotone. A limit below 60 can never work, because the 60-minute episode would not fit in any day. The total of 220 always works, because everything fits in one day. And a larger limit never needs more days than a smaller one. So the limits from 60 to 220 go from "no" to "yes" once.

60 90 220 no yes: 3 days or fewer first yes = the answer
The limits from 60 to 220 are the candidates. They change from no to yes exactly once, at 90.

In the trace below, lo starts at 60 and hi starts at 220, which is a known "yes". The row labelled day shows which day each episode is placed on for the current guess.

Smallest daily limit for 3 daysUse the arrows or ← → keys
lo = max(episodes), hi = sum(episodes)while lo < hi:  mid = lo + (hi - lo) // 2  if daysNeeded(mid) <= 3: hi = mid  else: lo = mid + 1return lo
  1. episodes
    040
    125
    260
    330
    445
    520
    lo
    60
    hi
    220
    checks
    0

    1The answer lies between 60, the longest episode, and 220, the total of all episodes.

  2. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    21
    32
    42
    52
    lo
    60
    hi
    140
    mid
    140
    days
    2
    checks
    1

    2The guess is 140. Day 1 holds 40 + 25 + 60 = 125, and adding 30 would make 155, so the rest goes on day 2. That is 2 days, which is at most 3, so the answer is 140 or smaller and hi = 140.

  3. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    32
    43
    53
    lo
    60
    hi
    100
    mid
    100
    days
    3
    checks
    2

    3The guess is 100. The three days hold 65, 90 and 65 minutes, so 100 works and hi = 100.

  4. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    33
    43
    54
    lo
    81
    hi
    100
    mid
    80
    days
    4
    checks
    3

    4The guess is 80. The 30 does not fit after 60 + 30 = 90, so it starts day 3, and the 20 does not fit after 30 + 45 = 75, so it needs day 4. That is too many days, so every limit up to 80 fails and lo = 81.

  5. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    32
    43
    53
    lo
    81
    hi
    90
    mid
    90
    days
    3
    checks
    4

    5The guess is 90. The episodes 60 and 30 add up to exactly 90, which fits, so 3 days are enough and hi = 90.

  6. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    33
    43
    54
    lo
    86
    hi
    90
    mid
    85
    days
    4
    checks
    5

    6The guess is 85. The episodes 60 and 30 no longer fit together, so this needs 4 days and lo = 86.

  7. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    33
    43
    54
    lo
    89
    hi
    90
    mid
    88
    days
    4
    checks
    6

    7The guess is 88. This still needs 4 days, so lo = 89.

  8. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    33
    43
    54
    lo
    90
    hi
    90
    mid
    89
    days
    4
    checks
    7

    8The guess is 89, which is one minute too small to fit 60 + 30 on one day. This needs 4 days, so lo = 90.

  9. episodes
    040
    125
    260
    330
    445
    520
    day
    01
    11
    22
    32
    43
    53
    answer
    90
    checks
    7

    9Now lo and hi are both 90, so the smallest limit that works is 90. This took 7 checks, where trying 60, 61, 62 and so on up to 90 would have taken 31.

1 / 9

Code

The code is split into a reusable firstYes search and the check that belongs to this problem. firstYes works for any problem whose answers go from no to yes, as long as hi is a "yes".

// Smallest x in [lo, hi] with isYes(x) true.
// isYes must go no, ..., no, yes, ..., yes, and isYes(hi) must be true.
function firstYes(lo, hi, isYes) {
  while (lo < hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    if (isYes(mid)) hi = mid; // mid works: the answer is mid or smaller
    else lo = mid + 1;        // mid fails: the answer is bigger
  }
  return lo;
}
 
// Assumes limit >= the longest episode.
function daysNeeded(episodes, limit) {
  let days = 1, today = 0;
  for (const minutes of episodes) {
    if (today + minutes > limit) { days++; today = 0; } // start a new day
    today += minutes;
  }
  return days;
}
 
function smallestDailyLimit(episodes, maxDays) {
  const lo = Math.max(...episodes);
  const hi = episodes.reduce((sum, m) => sum + m, 0);
  return firstYes(lo, hi, (limit) => daysNeeded(episodes, limit) <= maxDays);
}
 
smallestDailyLimit([40, 25, 60, 30, 45, 20], 3); // 90
# Smallest x in [lo, hi] with is_yes(x) true.
# is_yes must go no, ..., no, yes, ..., yes, and is_yes(hi) must be true.
def first_yes(lo, hi, is_yes):
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if is_yes(mid):
            hi = mid      # mid works: the answer is mid or smaller
        else:
            lo = mid + 1  # mid fails: the answer is bigger
    return lo
 
# Assumes limit >= the longest episode.
def days_needed(episodes, limit):
    days, today = 1, 0
    for minutes in episodes:
        if today + minutes > limit:  # start a new day
            days += 1
            today = 0
        today += minutes
    return days
 
def smallest_daily_limit(episodes, max_days):
    lo, hi = max(episodes), sum(episodes)
    return first_yes(lo, hi, lambda limit: days_needed(episodes, limit) <= max_days)
 
smallest_daily_limit([40, 25, 60, 30, 45, 20], 3)  # 90

Time and space cost

ApproachTimeSpaceWhy
Try every limit from the bottomO(n × R)O(1)R = hi − lo + 1 candidates, each checked in O(n).
Binary search on the answerO(n log R)O(1)About log₂ R checks, each O(n). Even R = 1,000,000,000 needs only 30 checks.

Variants

Finding the largest value that works

Some problems reverse the pattern: the answers go yes, …, yes, no, …, no, and you want the last "yes". Do not write a second template for this. Search for the first "no" with firstYes and subtract 1. For example, the integer square root of 30 is the largest x with x × x ≤ 30. The first x with x × x > 30 is 6, so the answer is 5.

Largest value that works
// Largest x with x * x <= n, for n >= 0.
function intSqrt(n) {
  // n + 1 is surely a "no", because (n + 1)² > n.
  return firstYes(0, n + 1, (x) => x * x > n) - 1;
}
 
intSqrt(30); // 5
# Largest x with x * x <= n, for n >= 0.
def int_sqrt(n):
    # n + 1 is surely a "no", because (n + 1)² > n.
    return first_yes(0, n + 1, lambda x: x * x > n) - 1
 
int_sqrt(30)  # 5

This is also the way to handle "maximise the minimum" problems, such as placing k items on a line so that the smallest gap between any two is as large as possible. The check is "can I place all k items with every gap at least d?". It is true for small d and false for large d, so you search for the first d where it fails and subtract 1.

Answers that are real numbers

When the answer is a real number, such as a speed or a length, there is no mid + 1 to step to, so the integer template does not apply. Keep the same idea but move the bounds to mid in both cases, and stop after a fixed number of iterations (100 is plenty for doubles) or when hi - lo is smaller than the precision the problem asks for. Do not loop on lo < hi with floating-point numbers, because the loop may never end.

When the technique does not apply

It does not apply when the check is not monotone, which means the answers do not change from no to yes only once. For example, "can I finish in exactly 3 days?" gives no for tiny limits, yes for some limits, and no again for huge limits that finish in 1 day. Asking for "at most 3 days" fixes this. It also does not apply when you cannot bound the answer, or when a direct formula or a single greedy pass already gives the answer, because then the search adds work without saving any.

Pitfalls

In the interview

The signals are in the wording of the problem. Look for "the minimum possible largest sum", "the smallest speed that finishes in time", "the largest size such that at least k pieces fit", or "the minimum capacity needed to ship within d days". Another clue is a huge range of possible answers, up to 10⁹ or more, together with a simple way to verify one candidate. Many problems of this type are classic ones, such as splitting an array into k parts with the smallest largest sum, or the slowest eating speed that finishes all piles in h hours. They all use the same template with a different check.

Interviewers usually focus on two things: whether you can state why the answers are monotone, and whether your bounds and your check are correct. Expect these questions.

  • "Why can you binary search here? The input is not sorted." The thing being searched is the range of candidate answers, not the input. If a value works, every larger value works too, so the candidates are ordered by yes and no, and that is all binary search needs.
  • "How did you choose the bounds?" The lower bound is the smallest value for which the check is meaningful, such as the longest single item. The upper bound is a value that certainly works, such as the total of all items. A looser bound only costs one or two extra checks, because the cost grows with the logarithm of the range.
  • "Why is the greedy check correct?" Filling each day as full as possible leaves the least work for the remaining days. Any other way to split the list can be changed into the greedy one without using more days, so the greedy count is the minimum for that limit.
  • "Can anything overflow?" In languages with fixed-size integers, the sum of all items can exceed 32 bits, so use a 64-bit type for hi and for the running total in the check. Computing mid as lo + (hi - lo) / 2 avoids overflow in lo + hi.
  • "What is the complexity?" It is O(n log R), where n is the cost of one check and R is the size of the range of candidates. For limits up to 10⁹ that is about 30 passes over the input.
  • "What if the answer is a decimal?" Halve the interval a fixed number of times, or until it is narrower than the required precision, and move the bounds to mid instead of mid + 1.
  • "Is there another way to solve this?" A dynamic programming solution exists for the splitting problem and takes O(n² × k) time, which is slower for large inputs. Binary search on the answer is the expected solution when the limits are large.
Quick check

The episodes are [40, 25, 60, 30, 45, 20] and the limit is 100 minutes. How many days does the greedy check need?

The candidate answers run from 1 to 1,000,000,000. About how many checks does binary search on the answer need?

Which question can you binary search on?

You want the largest x for which a check is true, and the answers go yes, …, yes, no, …, no. What do you do with firstYes?

What to practise next

As an exercise, work out by hand the smallest daily limit for the same episodes with 2 days, which is 125. The next module starts with Binary Trees, where the idea of discarding half of the data at each step becomes a data structure.