Binary search on the answer
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Until now, we have binary searched an input array that was already sorted. What if the input array is unsorted—like package weights [3, 2, 2, 4, 1, 4]—and the problem asks for the minimum ship capacity to deliver them in 3 days? You cannot sort the packages (they must ship in conveyor-belt order), yet you can binary search the possible answers!
A monotonic yes/no condition
Binary search on the answer searches a range of possible answers instead of an array, using a check that says whether a guessed answer is good enough.
Binary search on the answer finds the minimum (or maximum) x that works by guessing x and checking the guess with a fast yes/no helper canDo(x). It only works when canDo(x) is monotonic: its answers switch between false and true exactly once.
public class MonotonicCheck { static boolean canDo(int x, int n) { return (long) x * x <= n; // true for x, so also true for every smaller x }
public static void main(String[] args) { for (int x = 0; x <= 5; x++) { System.out.println("canDo(" + x + ") = " + canDo(x, 10)); } }}canDo(0) = true canDo(1) = true canDo(2) = true canDo(3) = true canDo(4) = false canDo(5) = false
So whenever a problem asks for the minimum x that works or the maximum x that works, ask: can I write a fast canDo(x), and is it monotonic?
Monotonic means the boolean outputs of canDo(x) across the range of possible answers [lo .. hi] never flip back and forth—they look like one clean step:
- Minimize
x([false, false, ..., false, true, true, ..., true]): if capacityxis big enough to ship all packages on time, then any capacity> xis also big enough! We want the firsttrue(lowerBound). - Maximize
x([true, true, ..., true, false, false, ..., false]): if integerxsatisfiesx * x <= n, then any non-negative integer< xalso satisfies it! We want the lasttrue.
- First
truetemplate (while (lo < hi)):mid = lo + (hi - lo) / 2;ifcanDo(mid)istrue, sethi = mid; else setlo = mid + 1. - Last
truetemplate (while (lo < hi)):mid = lo + (hi - lo + 1) / 2;(round up!) ifcanDo(mid)istrue, setlo = mid; else sethi = mid - 1.
lo = mid, we MUST round mid up via lo + (hi - lo + 1) / 2 (or use while (lo <= hi) with ans = mid; lo = mid + 1;) so a 2-element range [lo, lo + 1] never loops forever!Minimum ship capacity
In Capacity To Ship Packages Within D Days, packages with weights weights[] arrive in order on a conveyor belt and must be shipped within days days.
Example 1 · Brute force: try every capacity upward (O(n · sum) time, O(1) space)
public class ShipEveryCapacity { private static boolean canShip(int[] weights, int days, int cap) { int usedDays = 1, currentLoad = 0; for (int w : weights) { if (currentLoad + w > cap) { usedDays++; currentLoad = 0; } currentLoad += w; } return usedDays <= days; }
public static void main(String[] args) { int[] weights = new int[500]; int max = 0; for (int i = 0; i < weights.length; i++) { weights[i] = i % 20 + 1; max = Math.max(max, weights[i]); } int days = 25; int cap = max; int tried = 1; while (!canShip(weights, days, cap)) { cap++; tried++; } System.out.println("Minimum capacity: " + cap); System.out.println("Capacities tried: " + tried); }}Minimum capacity: 210 Capacities tried: 191
What this code does
- 500 packages weighing 1 to 20 must ship in 25 days. The loop tries 191 capacities (20 up to 210), and each try walks all 500 packages.
- It is slow because if capacity 210 works then 211 works too, and the loop never uses that single false-to-true switch.
Example 2 · Optimal: binary search on the capacity (O(n log sum) time, O(1) space)
public class ShipPackagesDemo { private static boolean canShip(int[] weights, int days, int cap) { int usedDays = 1, currentLoad = 0; for (int w : weights) { if (currentLoad + w > cap) { usedDays++; currentLoad = 0; } currentLoad += w; } return usedDays <= days; }
public static int shipWithinDays(int[] weights, int days) { int lo = 0, hi = 0; for (int w : weights) { lo = Math.max(lo, w); hi += w; } while (lo < hi) { int mid = lo + (hi - lo) / 2; if (canShip(weights, days, mid)) { hi = mid; // mid works; try smaller capacity } else { lo = mid + 1; } } return lo; }
public static void main(String[] args) { int[] weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; System.out.println("Min capacity for 5 days: " + shipWithinDays(weights, 5)); }}Min capacity for 5 days: 15
What this code does
- The answer space is [lo=10 .. hi=55]. At capacity 15, the 5 days carry [1..5], [6,7], [8], [9], [10].
- With capacity 14, it would take 6 days, so 15 is the first true in [10..55].
- Because "can ship" flips from false to true only once, each check discards half of the capacities: about log₂ 5,230 ≈ 13 checks instead of the 191 above.
In detail:
- What is the answer space
[lo .. hi]?
lo = max(weights): the ship must be able to carry the single heaviest package by itself.hi = sum(weights): a ship with capacity equal to the total weight ships everything in 1 day.
- How does
canShip(weights, days, cap)work?
- Greedily load packages onto today's ship until the next package would exceed
cap; then start a new day (usedDays++). ReturnusedDays <= daysin O(n) time.
- Total time: O(n log(sum - max)) time and O(1) space!
Order of execution
Binary search on the capacity
Tap the steps in the order the search runs them.
Minimum processing speed
In Minimum Processing Speed, there are piles[] of tasks and a worker has h hours (h >= piles.length). At processing speed k tasks/hour, a pile of size p takes ⌈ p / k ⌉ hours (in integer arithmetic: (p + k - 1) / k).
Example 3 · Minimum Processing Speed with ceiling division
public class ProcessingSpeedDemo { private static boolean canEatAll(int[] piles, int h, int speed) { long hours = 0; for (int p : piles) { hours += (p + speed - 1) / speed; // ceil(p / speed) } return hours <= h; }
public static int minProcessingSpeed(int[] piles, int h) { int lo = 1, hi = 0; for (int p : piles) hi = Math.max(hi, p); while (lo < hi) { int mid = lo + (hi - lo) / 2; if (canEatAll(piles, h, mid)) { hi = mid; } else { lo = mid + 1; } } return lo; }
public static void main(String[] args) { int[] piles = {3, 6, 7, 11}; System.out.println("Min speed for h=8: " + minProcessingSpeed(piles, 8)); }}Min speed for h=8: 4
What this code does
- At speed 4, the piles take ceil(3/4)=1, ceil(6/4)=2, ceil(7/4)=2, ceil(11/4)=3 hours -> 1+2+2+3 = 8 hours <= 8.
- At speed 3, they take 1+2+3+4 = 10 hours > 8, so 4 is the minimum feasible speed.
- Answer space:
lo = 1task/hour,hi = max(piles)(working faster than the largest pile never saves more than 1 hour per pile). - Feasibility check
canFinish(piles, h, k): sum(long) (p + k - 1) / kacross all piles and check iftotalHours <= h. (UselongfortotalHoursso10^9hours across many piles never overflowsint!)
Integer square root
In Sqrt(x), given a non-negative integer x, compute ⌊ √x ⌋ without Math.sqrt.
We want the largest integer mid in [0 .. x] such that mid * mid <= x ([true, true, ..., true, false, false]).
Example 4 · Integer Square Root (last true in [0..x])
public class IntegerSqrtDemo { public static int mySqrt(int x) { long lo = 0, hi = x; while (lo < hi) { long mid = lo + (hi - lo + 1) / 2; // round up when setting lo = mid! if (mid * mid <= x) { lo = mid; // mid works; try larger } else { hi = mid - 1; // mid is too large } } return (int) lo; }
public static void main(String[] args) { System.out.println("sqrt(8) = " + mySqrt(8)); System.out.println("sqrt(2147395600) = " + mySqrt(2147395600)); System.out.println("sqrt(Integer.MAX_VALUE) = " + mySqrt(Integer.MAX_VALUE)); }}sqrt(8) = 2 sqrt(2147395600) = 46340 sqrt(Integer.MAX_VALUE) = 46340
What this code does
- Casting (long) mid * mid prevents 32-bit int overflow when mid is around 10^9.
- Using mid = lo + (hi - lo + 1) / 2 ensures that when hi == lo + 1, mid equals hi, preventing an infinite loop on lo = mid.
Watch out for overflow: if x = Integer.MAX_VALUE (2,147,483,647), the initial mid is ≈ 10⁹, so mid * mid is ≈ 10¹⁸, which overflows 32-bit int! Cast to (long) mid * mid <= x (or check mid <= x / mid for mid > 0).
Next step
Check your understanding
10 quick questions