Algorithm · Searching · O(n log S)

Binary search on the answer

Binary search over possible answers instead of array positions, when a yes/no feasibility check is monotonic in the answer.

The full derivation, edge cases and exercises are in the lesson Binary search on the answer: the first true of a monotonic predicate. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Some optimization problems ask for the smallest value that works: the least ship capacity that delivers all packages in D days, the earliest time something becomes true. If every value above a working one also works, the answers form a sorted yes/no sequence, and binary search finds the boundary.

Each probe runs the feasibility check, so the total cost is the check’s cost times the logarithm of the answer range.

Steps

  1. Pick a range [lo, hi] guaranteed to contain the answer (here: the heaviest package to the total weight).
  2. Test the middle value with the feasibility check.
  3. If it works, the answer is at most mid; otherwise it is greater than mid.
  4. Stop when lo = hi: that is the smallest feasible value.

Invariants

What holds at every step; the correctness argument rests on these.

  • hi is always feasible; every value below lo is infeasible.
  • feasible(x) is monotonic: false … false, true … true.

Complexity

Binary search on the answer complexity
CaseTimeExtra spaceNotes
Whole searchO(n log S)O(1)S = size of the answer range; each check is a greedy O(n) pass.

When to use it

Use it when

  • The question is “smallest (or largest) x such that …” and checking one x is easy.
  • Constraints allow a check per candidate but not trying every candidate.

Avoid it when

  • The predicate is not monotonic: binary search can skip the true boundary.
  • A direct formula or a greedy pass gives the answer without searching.

Step through it

The interactive lab for binary search on the answer: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Data structures it uses

Problems, patterns and exercises

References