Binary Search on the Answer

When feasibility is monotonic in the answer, binary search over possible answers and check each with a greedy function.

Intermediate · about 5 hours · difficulty 4/5

Learn first: Binary Search

A powerful pattern: instead of searching an array, search the range of possible answers. If you can write a function feasible(x) that says whether answer x works, and feasibility is monotonic (if x works, every larger x also works), binary search finds the smallest working x.

Recognising it

Look for phrases like "minimise the maximum", "maximise the minimum", "smallest capacity such that", or "minimum speed to finish in time". The answer lives in a numeric range [low, high], and checking a single candidate is easier than finding the optimum directly.

Structure

  • Choose bounds: for Koko Eating Bananas, speed is in [1, max pile].
  • Write feasible(mid), usually a greedy O(n) scan: "with speed mid, how many hours does it take?".
  • Binary search with the first-true template. Total cost O(n log range).

Classic problems

  • Koko Eating Bananas, Capacity to Ship Packages Within D Days.
  • Split Array Largest Sum, Book Allocation, Painter's Partition (very common in Indian interviews).
  • Aggressive Cows / Magnetic Force Between Two Balls (maximise minimum distance).
  • Minimum Number of Days to Make m Bouquets.

Pitfalls

Wrong bounds (low must be feasible-or-not correctly, high must be definitely feasible), overflow when summing inside the check, and using it where feasibility is not monotonic. Always write one sentence proving monotonicity before coding.

Key concepts

  • Monotonic feasibility
  • Choosing search bounds
  • Greedy check function
  • Minimise the maximum: Split Array Largest Sum
  • Maximise the minimum: Aggressive Cows
  • k-th smallest via counting: Multiplication table

Mini project

Solve 7 problems: Koko Eating Bananas, Capacity to Ship Packages, Split Array Largest Sum, Book Allocation, Aggressive Cows, Minimum Days to Make m Bouquets, and Kth Smallest Number in Multiplication Table.

Check yourself

For Capacity to Ship Packages, why is the lower bound max(weights) and the upper bound sum(weights)?

Free resources