Binary search is usually taught as “find a value in a sorted array”. But it can do much more. If you can ask a yes/no question about a possible answer, and the answers switch from “no” to “yes” only once, you can binary search over the answers themselves. This trick, called binary search on the answer, solves many optimisation problems: the smallest capacity, the largest distance, the shortest time. This lesson shows how to spot these problems and write the search without off-by-one errors.
In this lesson you will learn
- What a monotonic yes/no condition is
- How to choose the search range
- Finding the smallest value that works (ship capacity)
- Finding the largest value that works (integer square root, placing cows)
- How to avoid infinite loops and overflow
You should know binary search in C and the greedy method.
The Idea
Suppose a check ok(x) is false for small x and true for all x from some point on:
x: 5 6 7 8 9 10 11 12 ...
ok(x): F F F F T T T T ...
^ the answer is the first T
Because the pattern switches only once, binary search can find the switch point by testing about log2(range) values, instead of testing every x. Each test may itself take O(n), so the total is O(n log range).
Smallest Value That Works
A ship must carry packages in the given order within D days. What is the smallest capacity that makes this possible? A bigger ship never needs more days, so the condition “fits in D days” is monotonic.
#include <stdio.h>
/* Ship packages within D days: smallest ship capacity that works */
static int days_needed(const int *w, int n, int cap) {
int days = 1, load = 0;
for (int i = 0; i < n; i++) {
if (load + w[i] > cap) { days++; load = 0; } /* start a new day */
load += w[i];
}
return days;
}
int main(void) {
int w[] = {3, 2, 2, 4, 1, 4, 5, 3};
int n = 8, D = 3;
int lo = 0, hi = 0;
for (int i = 0; i < n; i++) {
if (w[i] > lo) lo = w[i]; /* capacity must fit the heaviest package */
hi += w[i]; /* one day for everything always works */
}
printf("Search capacities %d to %d\n", lo, hi);
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int d = days_needed(w, n, mid);
printf(" try %2d -> %d days %s\n", mid, d, d <= D ? "(ok, try smaller)" : "(too slow)");
if (d <= D) hi = mid; /* mid works: answer is mid or smaller */
else lo = mid + 1; /* mid fails: answer is bigger */
}
printf("Smallest capacity for %d days: %d\n", D, lo);
return 0;
}
Output
Search capacities 5 to 24
try 14 -> 2 days (ok, try smaller)
try 9 -> 3 days (ok, try smaller)
try 7 -> 5 days (too slow)
try 8 -> 4 days (too slow)
Smallest capacity for 3 days: 9
- The lowest possible answer is the heaviest package (5), or that package could never be loaded. The highest is the total weight (24), which always fits in one day.
days_neededis a greedy check: load packages in order until the next one would overflow, then start a new day.- When
midworks, the answer could bemiditself, so we keep it withhi = mid. When it fails, the answer is bigger, solo = mid + 1. - The loop stops when
lo == hi. Only four checks were needed for 20 possible capacities. With capacity 9, the days are [3, 2, 2], [4, 1, 4] and [5, 3].
Largest Value That Works
Sometimes the pattern is reversed: true for small x and false for big x. Then we want the last true.
#include <stdio.h>
/* Integer square root by binary search on the answer */
static long isqrt(long x) {
long lo = 0, hi = x, ans = 0;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
if (mid == 0 || mid <= x / mid) { ans = mid; lo = mid + 1; } /* mid*mid <= x */
else hi = mid - 1;
}
return ans;
}
/* Aggressive cows: place k cows in stalls so the closest pair is as far apart as possible */
static int can_place(const int *s, int n, int k, int gap) {
int count = 1, last = s[0];
for (int i = 1; i < n; i++)
if (s[i] - last >= gap) { count++; last = s[i]; }
return count >= k;
}
int main(void) {
long xs[] = {16, 27, 1000000};
for (int i = 0; i < 3; i++) printf("isqrt(%ld) = %ld\n", xs[i], isqrt(xs[i]));
int stalls[] = {1, 2, 4, 8, 9}; /* already sorted */
int n = 5, k = 3;
int lo = 1, hi = stalls[n - 1] - stalls[0], best = 0;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (can_place(stalls, n, k, mid)) { best = mid; lo = mid + 1; }
else hi = mid - 1;
}
printf("Largest minimum distance for %d cows: %d\n", k, best);
return 0;
}
Output
isqrt(16) = 4
isqrt(27) = 5
isqrt(1000000) = 1000
Largest minimum distance for 3 cows: 3
- Integer square root: “mid × mid ≤ x” is true up to the answer and false after it. Writing it as
mid <= x / midavoids overflow when mid is large. - This version uses
lo <= hiand saves the best value found inans. It is an easy pattern to get right. - Aggressive cows: put 3 cows in stalls at 1, 2, 4, 8, 9 so the closest two are as far apart as possible. “Can we keep every gap at least g?” is true for small g and false for large g. The greedy check puts each cow in the first stall that is far enough from the last one. The answer is 3, for example stalls 1, 4 and 8.
Two Safe Templates
| Goal | Loop | When ok(mid) | Otherwise |
|---|---|---|---|
| First value that works | while (lo < hi), mid = lo + (hi − lo) / 2 | hi = mid | lo = mid + 1 |
| Last value that works | while (lo <= hi) | ans = mid; lo = mid + 1 | hi = mid − 1 |
To recognise these problems, look for phrases such as “minimum largest”, “maximum smallest”, “at least” or “within k days”, together with a check that is easy to run for one candidate value.
Common Mistakes
- A check that is not monotonic. Binary search then gives wrong answers with no warning.
- A range that misses the answer, for example starting the ship search at 1 instead of the heaviest package.
- Writing
lo = midwithwhile (lo < hi), which can loop forever when hi = lo + 1. - Overflow in
(lo + hi) / 2ormid * midfor large numbers.
Practice Exercises
Exercise 1. Koko eats bananas from piles {3, 6, 7, 11} at k bananas per hour, finishing one pile before starting another. What is the smallest k to finish within 8 hours?
Show answer
Hours for speed k is the sum of ceil(pile / k). k = 4 gives 1 + 2 + 2 + 3 = 8 hours, and k = 3 gives 1 + 2 + 3 + 4 = 10 hours. So the answer is 4.
Exercise 2. Why can’t we binary search the answer for “the number of pairs with sum 10”?
Show answer
There is no yes/no check that switches once as the candidate grows. Binary search on the answer needs a monotonic condition; counting problems usually do not have one.
Frequently Asked Questions
Can the answer be a real number?
Yes. Use doubles for lo and hi, and run a fixed number of iterations, such as 60, instead of testing lo < hi. Each iteration halves the range, so the error becomes tiny.
How is this different from ordinary binary search?
Ordinary binary search looks inside an array. Here there is no array: the “array” is the list of possible answers, and checking one entry means running a small algorithm.
Summary
- If ok(x) switches from false to true only once, binary search finds the switch point.
- Choose lo and hi so the answer must lie between them.
- Use
hi = midfor the first true, or saveansfor the last true. - The total time is the cost of one check times log of the range.
