Lesson 12 · Core algorithms

Binary Search on Answer

When the question asks for the smallest value that works (or the largest), and every value past the first good one also works, guess the middle of the range of answers, test it with a fast check, and throw away the half that cannot hold the boundary.

Binary Search on Answer concept diagramBars show how many days the packages 3, 2, 2, 4, 1, 4 need at each capacity from 4 to 16: 5, 4, then 3 for capacities 6 to 8, 2 up to 15, and 1 at 16. A dashed line marks the limit of 3 days. Below, a strip reads no for 4 and 5 and yes from 6 on. Arrows show the search probing 10, then 7, then 5, then 6, and stopping at 6, the first yes.days needed at each capacity · packages 3 2 2 4 1 4 · limit 3 daysD = 3544 · #353 · #463 · #2738292 · #110211212213214215116checknonoyesyesyesyesyesyesyesyesyesyesyesprobes: 10 yes → 7 yes → 5 no → 6 yesfirst yes = 6
1

The Idea: Guess the Answer, Then Check It

  1. Find the range: the smallest and largest values the answer could take.
  2. Write check(x): can the task be done with value x?
  3. Pick mid. If check(mid) is yes, the answer is mid or smaller; if no, it is larger.
  4. Repeat until the range is one value. That value is the answer.

Some problems are hard to solve directly but easy to verify. Ship packages in order over D days: what is the smallest daily capacity that works? Computing that number straight away is awkward. But if someone hands you a capacity, you can tell in one pass whether it is enough: load packages until the next one would not fit, start a new day, and count the days.

Binary search on answer turns that check into the solution. List every capacity that could possibly be the answer, ask the check about the middle one, and keep the half where the answer must be. The array being searched is not in memory at all; it is the line of candidate answers.

  • Hard to compute, easy to verify: that gap is the signal
  • The candidates are ordered numbers, so nothing needs sorting
2

Why It Works: The Check Flips Once

If capacity 6 ships everything in 3 days, capacity 7 does too: a bigger truck never needs more days. So across the range the answers to check() read no, no, …, no, yes, yes, …, yes. A yes/no test with that shape is called monotonic, and the answer is the first yes.

That one switch is what lets a single probe discard half the range. A yes at mid means every value above mid is also yes, so none of them can be the first one. A no means every value below mid is also no. This is the same halving as searching a sorted array, applied to a function instead of stored values.

  • Monotonic check: once yes, yes for every larger value (or every smaller one, for maximising)
  • Without that shape a probe tells you nothing about the other values
3

Setting the Range and the Check

Both ends of the range come from the problem. For shipping, a capacity below the heaviest package can never work, so lo = max(weights). A capacity equal to the total ships everything in one day, so hi = sum(weights). For weights 3, 2, 2, 4, 1, 4 and D = 3 that is 4 to 16.

The feasibility check is usually greedy and linear. Fill each day as full as possible, because leaving room early can only push packages to later days. The check counts 4 days at capacity 5 and 3 days at capacity 6, so the answer is 6.

Many problems that ask you to minimize the maximum follow this shape: the largest daily load, the largest pages given to one student, the largest subarray sum after a split. Ask "can every part stay at or under X?" and search X. The mirror form, maximise the minimum, places items as far apart as possible: Aggressive Cows asks whether three cows can stand at least X apart.

  • lo: the smallest value that could possibly be enough
  • hi: a value that is always enough
  • The check returns yes or no; it does not need to know the answer
Key reference

Terms, operations, and practical uses

Key terms

  • Answer rangeEvery value the answer could take, from lo to hi.
  • Feasibility checkA yes/no test of one candidate, usually a single greedy pass.
  • MonotonicOnce the check says yes, it says yes for every value beyond.
Implementation

Code in Python, C++ and Java

def days_needed(weights, cap):
    days, load = 1, 0
    for w in weights:
        if load + w > cap:
            days += 1
            load = 0
        load += w
    return days


def ship_within_days(weights, d):
    lo, hi = max(weights), sum(weights)
    checks = 0
    while lo < hi:
        mid = (lo + hi) // 2
        checks += 1
        if days_needed(weights, mid) <= d:
            hi = mid
        else:
            lo = mid + 1
    return lo, checks


def can_place(stalls, cows, gap):
    placed, last = 1, stalls[0]
    for s in stalls[1:]:
        if s - last >= gap:
            placed += 1
            last = s
    return placed >= cows


def largest_min_gap(stalls, cows):
    stalls = sorted(stalls)
    lo, hi = 1, stalls[-1] - stalls[0]
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if can_place(stalls, cows, mid):
            lo = mid
        else:
            hi = mid - 1
    return lo


weights = [3, 2, 2, 4, 1, 4]
for d in (3, 1, 6):
    cap, checks = ship_within_days(weights, d)
    print(f"days={d} capacity={cap} checks={checks}")
print("days at 5:", days_needed(weights, 5), "days at 6:", days_needed(weights, 6))
print("largest min gap:", largest_min_gap([1, 2, 4, 8, 9], 3))
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

int daysNeeded(const vector<int>& weights, int cap) {
    int days = 1, load = 0;
    for (int w : weights) {
        if (load + w > cap) {
            days++;
            load = 0;
        }
        load += w;
    }
    return days;
}

pair<int, int> shipWithinDays(const vector<int>& weights, int d) {
    int lo = *max_element(weights.begin(), weights.end());
    int hi = accumulate(weights.begin(), weights.end(), 0);
    int checks = 0;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        checks++;
        if (daysNeeded(weights, mid) <= d) hi = mid;
        else lo = mid + 1;
    }
    return {lo, checks};
}

bool canPlace(const vector<int>& stalls, int cows, int gap) {
    int placed = 1, last = stalls[0];
    for (size_t i = 1; i < stalls.size(); i++) {
        if (stalls[i] - last >= gap) {
            placed++;
            last = stalls[i];
        }
    }
    return placed >= cows;
}

int largestMinGap(vector<int> stalls, int cows) {
    sort(stalls.begin(), stalls.end());
    int lo = 1, hi = stalls.back() - stalls.front();
    while (lo < hi) {
        int mid = lo + (hi - lo + 1) / 2;
        if (canPlace(stalls, cows, mid)) lo = mid;
        else hi = mid - 1;
    }
    return lo;
}

int main() {
    vector<int> weights = {3, 2, 2, 4, 1, 4};
    for (int d : {3, 1, 6}) {
        auto [cap, checks] = shipWithinDays(weights, d);
        cout << "days=" << d << " capacity=" << cap << " checks=" << checks << "\n";
    }
    cout << "days at 5: " << daysNeeded(weights, 5) << " days at 6: " << daysNeeded(weights, 6) << "\n";
    cout << "largest min gap: " << largestMinGap({1, 2, 4, 8, 9}, 3) << "\n";
}
import java.util.Arrays;

public class Main {
    static int daysNeeded(int[] weights, int cap) {
        int days = 1, load = 0;
        for (int w : weights) {
            if (load + w > cap) {
                days++;
                load = 0;
            }
            load += w;
        }
        return days;
    }

    static int[] shipWithinDays(int[] weights, int d) {
        int lo = Arrays.stream(weights).max().getAsInt();
        int hi = Arrays.stream(weights).sum();
        int checks = 0;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            checks++;
            if (daysNeeded(weights, mid) <= d) hi = mid;
            else lo = mid + 1;
        }
        return new int[] {lo, checks};
    }

    static boolean canPlace(int[] stalls, int cows, int gap) {
        int placed = 1, last = stalls[0];
        for (int i = 1; i < stalls.length; i++) {
            if (stalls[i] - last >= gap) {
                placed++;
                last = stalls[i];
            }
        }
        return placed >= cows;
    }

    static int largestMinGap(int[] stalls, int cows) {
        int[] s = stalls.clone();
        Arrays.sort(s);
        int lo = 1, hi = s[s.length - 1] - s[0];
        while (lo < hi) {
            int mid = lo + (hi - lo + 1) / 2;
            if (canPlace(s, cows, mid)) lo = mid;
            else hi = mid - 1;
        }
        return lo;
    }

    public static void main(String[] args) {
        int[] weights = {3, 2, 2, 4, 1, 4};
        for (int d : new int[] {3, 1, 6}) {
            int[] r = shipWithinDays(weights, d);
            System.out.println("days=" + d + " capacity=" + r[0] + " checks=" + r[1]);
        }
        System.out.println("days at 5: " + daysNeeded(weights, 5) + " days at 6: " + daysNeeded(weights, 6));
        System.out.println("largest min gap: " + largestMinGap(new int[] {1, 2, 4, 8, 9}, 3));
    }
}
Watch it run

Step through it

Running on weights [3, 2, 2, 4, 1, 4] · days 3 · capacities 4..16

smallest capacity that ships everything within 3 dayschecks: 0capacity45678910111213141516lohi322414lo = heaviest package = 4 · hi = total weight = 16the answer is one of 13 capacities, not a position in an array
Step 1

Ship six packages in 3 days

Packages weigh 3, 2, 2, 4, 1, 4 and must ship in this order, a whole number per day, within 3 days. The answer is a capacity, so search the capacities. Below 4 the heaviest package never fits; at 16 everything ships on day 1. The answer is somewhere in 4..16.

Output
1 / 11
4

Cost and Edge Cases

The loop makes about log₂(hi − lo) probes and each probe runs the check. With an O(n) check the total is O(n log R), where R is the width of the answer range. For 500 packages weighing up to 500 each, R is at most 250,000, so about 18 checks replace trying every capacity in turn.

Three cases test the bounds. With D = 1 the answer is the total, 16. With D equal to the number of packages the answer is the heaviest one, 4. If D could be smaller than 1 the input is invalid, and the loop should not run.

  • Use lo + (hi − lo) / 2 in C++ and Java so the sum cannot overflow
  • The loop ends with lo = hi; no extra check is needed afterwards
5

Common Mistakes

An infinite loop when maximising. For the largest value that works the update is lo = mid on a yes. With mid = (lo + hi) / 2, the range lo = 3, hi = 4 gives mid = 3 forever. Round up instead: mid = (lo + hi + 1) / 2.

A check that is not monotonic. "Ships in exactly 3 days" is true for capacities 6, 7 and 8 and false on both sides. A probe at 10 says no, and the search runs right, away from the answer. Phrase the check as "within D days", which is true for 6 and every capacity above it.

A range that misses the answer. Starting at lo = 1 for shipping works but wastes probes; starting above the true answer silently returns the wrong value.

  • Maximising with lo = mid: round mid up
  • Test the check on a few values first and confirm it flips once
6

Problems That Use It

Koko Eating Bananas searches eating speeds, Capacity to Ship Packages Within D Days searches capacities, Split Array Largest Sum and Allocate Minimum Pages minimise the largest part, and Minimum Number of Days to Make m Bouquets searches days. Sqrt(x) is the smallest case: the largest x whose square stays at or under the input.

For searching stored sorted values, with lower and upper bound, see binary search. For other changes to the keep-left or keep-right rule, such as rotated arrays, see binary search variations.

  • Minimise the maximum: shipping, pages, array splits
  • Maximise the minimum: cows in stalls, gaps between items