Searching · O(n log S)
Binary search on the answer
Find the smallest capacity that passes a monotonic feasibility check.
The full explanation, derivation and practice are in the lesson Binary search on the answer: the first true of a monotonic predicate.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
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 >= 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 >= 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 >= 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 >= 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