03
Binary search on the answer (Binary Search Sub-pattern)
You aren't searching the input — you're searching the range of possible answers. Guess one, check it greedily, keep the half that still contains the best answer.
Signals in the problem statement
- ›
"minimum … such that …" / "maximum … such that …"
- ›
"within D days", "within H hours", "into k parts"
- ›
checking a single guess is easy and greedy
- ›
answer range is huge (up to 10⁹)
What makes it different
Two separate pieces: the range (smallest possible → surely enough) and the feasibility check (usually a greedy O(N) pass). Prove the check is monotonic before you halve.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Koko Eating BananasWalkthroughMediumBasic Anchor·LeetCode #875
- 2Capacity To Ship Packages Within D DaysWalkthroughMediumBasic Reinforcement·LeetCode #1011
- 3Minimum Number of Days to Make m BouquetsWalkthroughMediumSlight Variation·LeetCode #1482
- 4Split Array Largest SumWalkthroughHardInterview-Level·LeetCode #410
Template
answer-template.cpp
// Smallest speed k so that all piles are eaten within h hours (Koko).
// Only the range [lo, hi] and feasible() change between problems.
bool feasible(vector<int>& piles, int h, int k) {
long long hours = 0;
for (int p : piles) hours += (p + k - 1) / k; // ceil(p / k)
return hours <= h;
}
int smallestWorking(vector<int>& piles, int h) {
int lo = 1; // smallest answer that could ever work
int hi = *max_element(piles.begin(), piles.end()); // this one surely works
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (feasible(piles, h, mid)) hi = mid; // works: maybe something smaller works too
else lo = mid + 1; // fails: everything smaller fails too
}
return lo;
}Remember this · Binary Search
Trigger
Sorted data, "minimum X such that…", "maximum X such that…", rotated arrays, answers that are monotonic (if X works, X+1 also works).
Think
Is there a yes/no question whose answers look like NNNNYYYY? Then binary search for the first Y.
Key question
What is my check function, and is it monotonic?