AlgoTales · Roadmap

Binary search on answer

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Sometimes the thing you search for is not an item in a list but a number like a speed, a size or a deadline. If you can test "does this value work?" and the answers switch cleanly from no to yes, you can binary search over the possible answers.

Practical use cases

  • Web app: Smallest delivery truck capacity. A logistics dashboard must ship 500 parcels in order within 5 days. The planner guesses a capacity, simulates loading, and checks if 5 days are enough. If yes, it tries a smaller truck; if no, a larger one. In about 15 guesses it finds the smallest capacity that works.
  • Web app: Rate limit for an API. A team wants the lowest requests-per-minute limit that still lets 99 percent of real users through. They replay yesterday traffic against a guessed limit and check the result. Halving the guess range finds the right value in a few replays instead of dozens.
  • System: Resource planning in the cloud. Capacity planners search for the smallest number of servers that handles a test load. Each trial is a heavy simulation, so trying every possible number one at a time would take days, whereas guessing by halves needs only a few runs.

The story: Guessing the Answer Itself

Zoya's big sister was getting married and the family needed 30 laddus. Three old machines made one laddu every 2, 3 and 5 minutes. "How long until we have 30?" asked Zoya. Nobody could just say it. Counting laddus minute by minute would be slow.

Mira had a funny idea: "Let us not calculate the answer. Let us guess it!" Guess 30 minutes. How many laddus is that? 15 + 10 + 6 = 31. Enough! So 30 works, maybe even less would. Guess 15 minutes: 7 + 5 + 3 = 15. Not enough, so the answer is bigger than 15.

Notice the pattern: if some time works, any longer time also works. Times that fail all sit on the left, times that work sit on the right, just like a sorted list of "no, no, no, yes, yes, yes". And a sorted list of yes/no can be halved! This is binary search on the answer: pick a range of possible answers, write a little check function ("is this guess enough?"), and keep halving the range. The "list" never exists in memory; it is imaginary.

How to spot this problem, and where you need it

You must find the smallest or largest value that satisfies a condition, such as capacity, speed or days, and you can check any guessed value easily but cannot compute it directly.

Signs you need it

  • The problem says "minimise the maximum", "smallest value such that", "largest value that still works" or "within D days".
  • You can write a simple yes/no check for a given number, and if 10 works then 11 surely works too.
  • Trying every possible number one by one is slow because the range is huge, such as up to a billion.

Where to use it in a project

  • Capacity and limit planning: batch sizes, shipment loads, rate limits, timeouts.
  • Scheduling and work-splitting features where you want the shortest finish time.

The solution

Decide the lowest and highest possible answer. Take the middle value and run your yes/no check on it. If it works, remember it and try a smaller value; if it fails, try a larger one. Repeat until the range closes. The check is a plain loop over the data, and the halving keeps the number of checks small.

Payoff: Before: testing every capacity from 1 to 1,000,000. After: about 20 tests to find the exact best value.

Explain it like I am 8

Someone asks, "How long will it take?" Instead of working it out, you say a guess like "30 minutes", and just check: "Would 30 minutes be enough?" If yes, try less. If no, try more. Each answer cuts the possible guesses in half, like guess-the-number!

How it works, step by step

  1. Decide the range of possible answers: the smallest it could be (low) and the biggest it could be (high).
  2. Write a check: feasible(guess) says yes or no. It must be monotone: once yes, always yes for bigger guesses (or the other way round).
  3. Guess the middle. If the check says yes, the answer is this or smaller, high = mid. If no, low = mid + 1.
  4. Repeat until low meets high. That number is the smallest guess that works.
  5. Cost: about log(range) checks, each taking the time of the check function.

The code in four languages

PHP

<?php
// How many laddus do the machines make in $minutes?
function laddusMade(array $times, int $minutes): int {
    $total = 0;
    foreach ($times as $t) {
        $total += intdiv($minutes, $t);     // each machine: whole laddus only
    }
    return $total;
}

// Smallest number of minutes that gives at least $need laddus.
function minMinutes(array $times, int $need): int {
    $low = 1;                               // best imaginable
    $high = min($times) * $need;            // fastest machine alone always works
    while ($low < $high) {
        $mid = intdiv($low + $high, 2);
        if (laddusMade($times, $mid) >= $need) {
            $high = $mid;                   // works: try smaller (keep mid)
        } else {
            $low = $mid + 1;                // too few: need more time
        }
    }
    return $low;
}

echo minMinutes([2, 3, 5], 30), "\n";       // 30

JavaScript

// How many laddus do the machines make in the given minutes?
function laddusMade(times, minutes) {
  let total = 0;
  for (const t of times) {
    total += Math.floor(minutes / t);       // each machine: whole laddus only
  }
  return total;
}

// Smallest number of minutes that gives at least "need" laddus.
function minMinutes(times, need) {
  let low = 1;                              // best imaginable
  let high = Math.min(...times) * need;     // fastest machine alone always works
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (laddusMade(times, mid) >= need) {
      high = mid;                           // works: try smaller (keep mid)
    } else {
      low = mid + 1;                        // too few: need more time
    }
  }
  return low;
}

console.log(minMinutes([2, 3, 5], 30));     // 30

Java

public class Main {
    // How many laddus do the machines make in the given minutes?
    static int laddusMade(int[] times, int minutes) {
        int total = 0;
        for (int t : times) {
            total += minutes / t;               // each machine: whole laddus only
        }
        return total;
    }

    // Smallest number of minutes that gives at least "need" laddus.
    static int minMinutes(int[] times, int need) {
        int fastest = Integer.MAX_VALUE;
        for (int t : times) fastest = Math.min(fastest, t);
        int low = 1;                            // best imaginable
        int high = fastest * need;              // fastest machine alone always works
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (laddusMade(times, mid) >= need) {
                high = mid;                     // works: try smaller (keep mid)
            } else {
                low = mid + 1;                  // too few: need more time
            }
        }
        return low;
    }

    public static void main(String[] args) {
        System.out.println(minMinutes(new int[]{2, 3, 5}, 30));     // 30
    }
}

Go

package main

import (
	"fmt"
	"slices"
)

// laddusMade: how many laddus do the machines make in the given minutes?
func laddusMade(times []int, minutes int) int {
	total := 0
	for _, t := range times {
		total += minutes / t // each machine: whole laddus only
	}
	return total
}

// minMinutes returns the smallest number of minutes that gives at least need laddus.
func minMinutes(times []int, need int) int {
	low := 1                         // best imaginable
	high := slices.Min(times) * need // fastest machine alone always works
	for low < high {
		mid := low + (high-low)/2
		if laddusMade(times, mid) >= need {
			high = mid // works: try smaller (keep mid)
		} else {
			low = mid + 1 // too few: need more time
		}
	}
	return low
}

func main() {
	fmt.Println(minMinutes([]int{2, 3, 5}, 30)) // 30
}

Time: O(n log R) · Extra space: O(1). R is the size of the range of answers (here 60); each of the ~log R guesses runs a check that reads n machines.

Watch out for

  • Using it when the check is not monotone: if "yes" and "no" are mixed up in the range, halving breaks.
  • A starting range that does not contain the true answer, for example a high that is too small.
  • Writing low = mid instead of mid + 1 and looping forever.

Quick check

  1. What are we actually searching in "binary search on the answer"?
    • A sorted array
    • A hash table
    • The range of possible answers
  2. What must be true about the check function?
    • It must be fast to write
    • It must return a number
    • Once a guess works, bigger (or smaller) guesses must also work
  3. If the guess works and we want the smallest answer, we set...
    • high = mid
    • low = mid + 1
    • high = mid + 1