M17 · Binary Search Patterns

Binary Search on the Answer

Binary search does not need an array. Whenever a yes/no question flips from "no" to "yes" exactly once as a number grows, you can binary search for the flip. This lesson turns "what is the smallest capacity that works?" into a predicate, proves it is monotonic, and searches it with the lower-bound loop.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M17 Binary Search Patterns · 1 of 1 lessons available

You will be able to

  • Recognise when an optimisation question ("smallest x such that …") can be answered by binary searching over x.
  • Write a feasibility predicate and argue that it is monotonic.
  • Choose correct search bounds and use the half-open lower-bound loop to find the first true.
  • State the running time O(n · log(range)) and compare it with a linear scan over candidates.
  • Keep the candidate range in 64-bit integers in C#, Java and C++, and use the library partition-point searches where they exist.

Helpful before this lesson

    Guidance only. Those modules are planned; the essentials are recapped here.

    Visual walkthrough

    The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

    Mental model

    The binary search lesson searched a sorted array: compare the middle element, discard half. What it really relied on was weaker than sortedness. It only needed a yes/no question that is "no" for every position up to some point and "yes" from there on:

    candidate:  10   11   12   13   14   15   16   17  …  55
    works?      no   no   no   no   no   yes  yes  yes …  yes
                                         ↑ the first yes

    Such a question is called a monotonic predicate. If you can evaluate it for any candidate, you can binary search for the first "yes" without ever storing the candidates. The candidates are not array elements; they are possible answers, hence the name.

    The example: the smallest daily capacity

    Packages with weights w[0..n−1] must be delivered in the given order. Each day a truck takes the next packages in line as long as their total stays within its capacity. What is the smallest capacity that delivers everything within days days?

    Trying capacities one by one works but can be slow: the answer can be as large as the total weight. Binary search on the answer needs three ingredients.

    1. A predicate

    canShip(capacity): load greedily, starting a new day when the next package does not fit, and report whether at most days days were needed.

    canShip(capacity):
        used = 1, load = 0
        for w in weights:
            if load + w > capacity:
                used += 1, load = 0
                if used > days: return false      # stop early
            load += w
        return true

    Greedy loading is optimal for a fixed capacity: putting a package on today's truck whenever it fits can never force more days later, because any schedule that postpones it leaves at least as much remaining work for the following days. It runs in O(n).

    2. Monotonicity

    If a capacity c works, every larger capacity works too: run the same day-by-day schedule on a bigger truck and every day still fits. So the predicate is false … false true … true over capacities, exactly the shape binary search needs. The lab's Predicate results panel shows each test; every failing capacity is smaller than every working one.

    Monotonicity is the part to prove for every new problem. If it does not hold, binary search returns a confident, wrong answer.

    3. Bounds that surely contain the answer

    • low = the heaviest package. Below that, one package cannot be loaded at all.
    • high = the total weight. Then everything goes on day one, so canShip(high) is true.

    With no packages both are 0 and the answer is 0 without a single test.

    The search: the first true

    This is the lower-bound loop from the binary search lesson, with values[mid] < target replaced by "the predicate is false at mid":

    low = max(weights), high = sum(weights)    # answer in [low, high]
    while low < high:
        mid = low + (high - low) / 2
        if canShip(mid): high = mid            # mid works: the first true is mid or earlier
        else:            low  = mid + 1        # mid fails: so does everything below it
    return low

    Invariant: the first working capacity is in [low, high]. It holds initially by the choice of bounds; high = mid keeps it because mid itself works; low = mid + 1 keeps it because mid and everything below fail. When low == high, that single candidate is the answer. Because mid < high always, every iteration shrinks the range, so the loop terminates.

    On the lab's first preset (weights 1 to 10, five days) the candidates are 10…55. The tests run 32 ✓, 21 ✓, 15 ✓, 12 ✗, 14 ✗, and the range closes on 15: five predicate calls for 46 candidates. The Large weights preset has 4,161 candidates and needs 12.

    Complexity

    With n packages and R = sum − max + 1 candidate capacities:

    Approach Predicate calls Time Extra space
    Linear scan upward from max up to R O(n · R) O(1)
    Binary search on the answer at most ⌈log₂ R⌉ O(n · log R) O(1)

    R can be enormous (weights up to 10⁹ make it about 10⁹ · n), yet log₂ R stays small: about 30 plus log₂ n. The Package checks metric counts the real work inside canShip; the early exit when a day too many is needed makes failing tests cheaper than successful ones.

    Recognising the pattern

    Look for these signals:

    • the question asks for the minimum (or maximum) value of something, such as a capacity, a speed, a time, a distance or a size;
    • checking whether a given value is good enough is much easier than computing the best value directly;
    • making the value larger (or smaller) can only turn a "no" into a "yes", never back.

    The same skeleton answers "the smallest speed to finish in h hours", "the largest minimum distance between k placed items", "the smallest maximum part sum when splitting into k parts" (the capacity problem in disguise) and "the first day on which something has happened". For a maximum, search for the last true instead: flip the roles of the branches, or search for the first false and subtract one.

    A boolean array works too: the problem bank's Find the first broken build asks for the first true in a list of build results, the same lower bound over indices. Over sorted values, Where does a value start and end? uses the predicates value ≥ target and value > target.

    Language notes

    Overflow. The upper bound is a sum of weights, which can exceed 2³¹ − 1 even when every weight fits in an int. The listings keep low, high, mid, the capacity and the daily load in long (C#, Java) or std::int64_t (C++), and compute mid = low + (high − low) / 2, which never exceeds high. In C++, signed overflow would be undefined behaviour, not just a wrong number. The C#, Java and C++ tests use three weights of int.MaxValue / INT_MAX, so the answer itself is beyond 32 bits. Python integers have arbitrary precision, so its listing keeps the simpler (low + high) // 2.

    Library searches over a predicate.

    Language First true over a range of numbers Notes
    C# no built-in for a predicate Array.BinarySearch needs a materialised, sorted array
    Python 3.10+ low + bisect.bisect_left(range(low, high + 1), True, key=pred) range is indexable without being stored; key is applied to the candidates, and False < True
    Java no built-in for a predicate Arrays.binarySearch / Collections.binarySearch need a stored array or list
    C++20 *std::ranges::partition_point(std::views::iota(low, high + 1), [&](auto c) { return !can_ship(c); }) partition_point returns the first element for which the predicate is false, so negate "works"

    Writing the loop yourself, as the listings do, is usually clearer and makes the bounds explicit.

    The teaching implementation

    MinCapacity / min_capacity and CanShip / can_ship are written the same way in all four languages, so the lab highlights the matching lines; the predicate's steps are traced as part of each test. Every language reads one shared fixture (no packages, one package, one day, more days than packages, equal weights, weights near the visualization limit) whose expected values come from a linear scan, not from the binary search. Each language also compares the search with a linear scan on 1,000 random inputs and checks that the predicate really is monotonic over every capacity in the range.

    Common mistakes

    • No monotonicity proof. The search runs fine on a non-monotonic predicate and returns garbage.
    • A lower bound that is too low. With low = 1, canShip would be asked about capacities that cannot hold the heaviest package; the greedy loop as written then miscounts days instead of failing.
    • Mixing loop styles. while low < high goes with high = mid and low = mid + 1; using low = mid loops forever when high = low + 1.
    • 32-bit sums. high = sum(weights) overflows long before the weights look large.
    • Returning mid instead of low after the loop: the last mid tested may have failed.

    Edge cases

    • No packages: low = high = 0; return 0 without testing.
    • One day: every test below the total fails; the answer is the total.
    • At least as many days as packages: the heaviest package (the lower bound) works.
    • All weights equal: the answer is that weight times ⌈n / days⌉.

    Worked practice

    1. Weights [7, 2, 5, 10, 8], two days. What are the bounds, and what is the answer?

    Answer

    Bounds [10, 32]. The answer is 18: day 1 takes 7 + 2 + 5 = 14, day 2 takes 10 + 8 = 18. With 17, day 2 would need 10 + 8 = 18 > 17, so a third day is needed.

    2. Why is low = mid + 1 safe when canShip(mid) is false?

    Answer

    By monotonicity, if mid fails, every smaller capacity fails too, so none of low..mid can be the first working capacity.

    3. How many predicate calls does the search need at most when the range holds 1,000 candidates?

    Answer

    ⌈log₂ 1000⌉ = 10. Each call at least halves the range: 1000 → 500 → 250 → 125 → 63 → 32 → 16 → 8 → 4 → 2 → 1.

    4. You want the largest capacity that still needs at least 3 days. How does the loop change?

    Answer

    The predicate "needs ≥ 3 days" is true … true false … false (bigger trucks need fewer days). Search for the first capacity where it is false, then subtract one; or binary search for the last true with low = mid and an upward-rounding midpoint mid = low + (high − low + 1) / 2.

    Summary

    • Binary search needs a monotonic yes/no question, not an array.
    • Search on the answer: bounds that surely contain the answer, an O(n) feasibility predicate, and the lower-bound loop for the first true.
    • Prove monotonicity for each problem; the code cannot check it for you.
    • O(n · log R) instead of O(n · R); keep the range in 64-bit integers in C#, Java and C++.

    Full implementation

    The capacity search in four languages, each checked against one shared fixture (no packages, one package, one day, more days than packages, equal and extreme weights) and 1,000 random inputs compared with a linear scan upward from the heaviest package, plus a check that the predicate is monotonic and totals beyond the 32-bit limit.

    namespace Bekadan.Dsa.Examples.Searching;
     
    /// <summary>
    /// Binary search on the answer: the smallest daily capacity that ships every
    /// package, in the given order, within <c>days</c> days.
    /// The search runs over capacities [max, sum], not over the array, using the
    /// monotonic predicate <see cref="CanShip"/> (false … false true … true).
    /// O(n log(sum - max)) time, O(1) extra space. Capacities are <see cref="long"/>:
    /// the total weight of many packages can exceed int.MaxValue.
    /// </summary>
    public static class SearchOnAnswer
    {
        /// <summary>Weights must be positive and days &gt;= 1. No packages: 0.</summary>
        public static long MinCapacity(ReadOnlySpan<int> weights, int days)
        {
            if (days < 1) throw new ArgumentOutOfRangeException(nameof(days), "Use at least one day.");
            long low = 0, high = 0;
            foreach (int w in weights)
            {
                low = Math.Max(low, w);  // smaller than the heaviest package: impossible
                high += w;               // the total: everything fits on day 1
            }
            while (low < high)
            {
                long mid = low + (high - low) / 2;
                if (CanShip(weights, days, mid))
                    high = mid;     // mid works; the first working capacity is mid or smaller
                else
                    low = mid + 1;  // mid fails, and so does everything below it
            }
            return low;
        }
     
        /// <summary>
        /// Greedy check: load packages in order, starting a new day when the next
        /// one does not fit. Assumes capacity &gt;= every weight.
        /// </summary>
        public static bool CanShip(ReadOnlySpan<int> weights, int days, long capacity)
        {
            int used = 1;
            long load = 0;
            foreach (int w in weights)
            {
                if (load + w > capacity)
                {
                    used++;
                    load = 0;
                    if (used > days) return false;  // stop early: already too many days
                }
                load += w;
            }
            return true;
        }
    }
    

    Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/SearchOnAnswer.cs

    """Binary search on the answer: the smallest daily capacity that ships every
    package, in the given order, within `days` days.
     
    The search runs over capacities [max, sum], not over the list, using the
    monotonic predicate can_ship (False ... False True ... True).
    O(n log(sum - max)) time, O(1) extra space. Python ints never overflow.
    """
     
    from collections.abc import Sequence
     
     
    def min_capacity(weights: Sequence[int], days: int) -> int:
        """Weights must be positive and days >= 1. No packages: 0."""
        if days < 1:
            raise ValueError("use at least one day")
        low, high = 0, 0
        for w in weights:
            low = max(low, w)  # smaller than the heaviest package: impossible
            high += w  # the total: everything fits on day 1
        while low < high:
            mid = (low + high) // 2
            if can_ship(weights, days, mid):
                high = mid  # mid works; the first working capacity is mid or smaller
            else:
                low = mid + 1  # mid fails, and so does everything below it
        return low
     
     
    def can_ship(weights: Sequence[int], days: int, capacity: int) -> bool:
        """Greedy check: load in order, starting a new day when the next package
        does not fit. Assumes capacity >= every weight."""
        used = 1
        load = 0
        for w in weights:
            if load + w > capacity:
                used += 1
                load = 0
                if used > days:
                    return False  # stop early: already too many days
            load += w
        return True
    

    Tested on CPython 3.14.0 · examples/python/dsa_examples/search_on_answer.py

    package dev.bekadan.dsa.searching;
     
    /**
     * Binary search on the answer: the smallest daily capacity that ships every
     * package, in the given order, within {@code days} days. The search runs over
     * capacities [max, sum], not over the array, using the monotonic predicate
     * {@link #canShip} (false ... false true ... true). O(n log(sum - max)) time,
     * O(1) extra space. Capacities are {@code long}: the total weight of many
     * packages can exceed Integer.MAX_VALUE.
     */
    public final class SearchOnAnswer {
        private SearchOnAnswer() {
        }
     
        /** Weights must be positive and days &gt;= 1. No packages: 0. */
        public static long minCapacity(int[] weights, int days) {
            if (days < 1) {
                throw new IllegalArgumentException("use at least one day");
            }
            long low = 0, high = 0;
            for (int w : weights) {
                low = Math.max(low, w); // smaller than the heaviest package: impossible
                high += w; // the total: everything fits on day 1
            }
            while (low < high) {
                long mid = low + (high - low) / 2;
                if (canShip(weights, days, mid)) {
                    high = mid; // mid works; the first working capacity is mid or smaller
                } else {
                    low = mid + 1; // mid fails, and so does everything below it
                }
            }
            return low;
        }
     
        /**
         * Greedy check: load packages in order, starting a new day when the next
         * one does not fit. Assumes capacity &gt;= every weight.
         */
        public static boolean canShip(int[] weights, int days, long capacity) {
            int used = 1;
            long load = 0;
            for (int w : weights) {
                if (load + w > capacity) {
                    used++;
                    load = 0;
                    if (used > days) {
                        return false; // stop early: already too many days
                    }
                }
                load += w;
            }
            return true;
        }
    }
    

    Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/SearchOnAnswer.java

    #pragma once
     
    #include <algorithm>
    #include <cstdint>
    #include <span>
    #include <stdexcept>
     
    namespace bekadan::dsa {
     
    // Binary search on the answer: the smallest daily capacity that ships every
    // package, in the given order, within `days` days. The search runs over
    // capacities [max, sum], not over the span, using the monotonic predicate
    // can_ship (false ... false true ... true). O(n log(sum - max)) time, O(1)
    // extra space. Capacities are std::int64_t: the total weight can exceed INT_MAX.
     
    // Greedy check: load packages in order, starting a new day when the next one
    // does not fit. Assumes capacity >= every weight.
    inline bool can_ship(std::span<const int> weights, int days, std::int64_t capacity) {
        int used = 1;
        std::int64_t load = 0;
        for (const int w : weights) {
            if (load + w > capacity) {
                ++used;
                load = 0;
                if (used > days) return false;  // stop early: already too many days
            }
            load += w;
        }
        return true;
    }
     
    // Weights must be positive and days >= 1 (throws std::invalid_argument otherwise
    // for days). No packages: 0.
    inline std::int64_t min_capacity(std::span<const int> weights, int days) {
        if (days < 1) throw std::invalid_argument("use at least one day");
        std::int64_t low = 0, high = 0;
        for (const int w : weights) {
            low = std::max<std::int64_t>(low, w);  // smaller than the heaviest package: impossible
            high += w;                              // the total: everything fits on day 1
        }
        while (low < high) {
            const std::int64_t mid = low + (high - low) / 2;
            if (can_ship(weights, days, mid)) {
                high = mid;  // mid works; the first working capacity is mid or smaller
            } else {
                low = mid + 1;  // mid fails, and so does everything below it
            }
        }
        return low;
    }
     
    }  // namespace bekadan::dsa
    

    Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/search_on_answer.hpp

    References