Binary Search · Pattern 7 of 8
Binary search on the answer
The most important pattern for interviews. You cannot find the answer directly, but you can check a guess. If "k works" means every bigger (or smaller) k also works, binary search the guess.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- "Minimum speed / capacity / days such that …" or "maximum distance / size such that …"
- Checking one candidate is a simple greedy pass over the input
- The answer is a number in a known range, often up to 10⁹
The template
// smallest value that works; works() goes false ... false, true ... true
int minFeasible(int lo, int hi) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (works(mid)) hi = mid; // works: try smaller
else lo = mid + 1; // too small
}
return lo;
}
// largest value that works; works() goes true ... true, false ... false
int maxFeasible(int lo, int hi) {
while (lo < hi) {
int mid = lo + (hi - lo + 1) / 2; // round up because we set lo = mid
if (works(mid)) lo = mid; // works: try bigger
else hi = mid - 1; // too big
}
return lo;
}
// Koko: works(k) = total hours at speed k <= h, searched over [1, max pile] def min_feasible(lo, hi, works): # False ... False, True ... True
while lo < hi:
mid = (lo + hi) // 2
if works(mid):
hi = mid # works: try smaller
else:
lo = mid + 1 # too small
return lo
def max_feasible(lo, hi, works): # True ... True, False ... False
while lo < hi:
mid = (lo + hi + 1) // 2 # round up because we set lo = mid
if works(mid):
lo = mid # works: try bigger
else:
hi = mid - 1 # too big
return lo
# Koko: min_feasible(1, max(piles), lambda k: sum(-(-p // k) for p in piles) <= h) // smallest value that works; works() goes false ... false, true ... true
int minFeasible(int lo, int hi, function<bool(int)> works) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (works(mid)) hi = mid; // works: try smaller
else lo = mid + 1; // too small
}
return lo;
}
// largest value that works; works() goes true ... true, false ... false
int maxFeasible(int lo, int hi, function<bool(int)> works) {
while (lo < hi) {
int mid = lo + (hi - lo + 1) / 2; // round up because we set lo = mid
if (works(mid)) lo = mid; // works: try bigger
else hi = mid - 1; // too big
}
return lo;
} // smallest value that works; works() goes false ... false, true ... true
function minFeasible(lo, hi, works) {
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (works(mid)) hi = mid; // works: try smaller
else lo = mid + 1; // too small
}
return lo;
}
// largest value that works; works() goes true ... true, false ... false
function maxFeasible(lo, hi, works) {
while (lo < hi) {
const mid = Math.floor((lo + hi + 1) / 2); // round up because we set lo = mid
if (works(mid)) lo = mid; // works: try bigger
else hi = mid - 1; // too big
}
return lo;
} The variations
-
1Minimise: the smallest value that works
Slowest speed, smallest capacity, fewest days, smallest divisor, the smallest "largest part". Guess mid, run a greedy check, keep the left half when it works.
Now you solve- Capacity To Ship Packages Within D Days Medium Stuck? solution
- Find the Smallest Divisor Given a Threshold Medium Stuck? ▶ video
- Minimum Number of Days to Make m Bouquets Medium Stuck? ▶ video
- Minimum Limit of Balls in a Bag Medium Stuck? solution
- Split Array Largest Sum Hard Stuck? solution
- House Robber IV Medium Stuck? ▶ video
-
2Maximise: the largest value that works
Largest minimum distance, largest tastiness, most tasks. The check flips: true, true, … false. Round mid up and keep the right half when it works.
Now you solve -
3Count to find the kth
The kth smallest value is the smallest x with at least k values ≤ x. Counting values ≤ x in a sorted matrix or a multiplication table is a quick O(n) walk.
Now you solve -
4Real-valued answers
When the answer is a decimal (a distance, a line position), binary search on doubles for a fixed number of rounds, keeping the same works / does-not-work logic.
Now you solve -
5Math in the check
The check is a formula rather than a pass over an array: the smallest k with 1 + 2 + … + k ≥ target, or a base whose digit sum equals n.
Now you solve
Mistakes to avoid
- Picking the wrong range: the low end must be a possible answer (often 1 or the max element), the high end one that surely works (the sum, the max).
- A check that is not monotonic. Say out loud why "k works" implies "k + 1 works" before you code.
- Summing hours or pieces in an int: the total can pass 2³¹. Use long.
- Real-valued answers: loop a fixed 60–100 times, or until hi − lo < 1e-6, instead of
lo < hi.
Lesson done
Next: Binary search on a partition →Mark it done once you can write the template from memory and you have solved the worked examples yourself.