Binary Search on Answer
Binary search over possible answers when a yes/no check flips only once.
- inside the window
- result
- ruled out
- removed / popped
The answer is between 1 and 11
Speed 11 finishes any pile in an hour, so it always works.
VARIABLES
- lo
- 1
- hi
- 11
- mid
- -
- hours
- -
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Instead of searching an array, search the range of candidate answers. A feasibility check says whether an answer works - and if it does, every larger (or smaller) one does too.
Why it matters
“Find the smallest X that works” becomes O(log range) checks, each usually O(n).
Think of it like this
Picking the smallest suitcase: if size 50 fits everything, so does 60 - so try the middle size and halve.
Use it when
- “Minimize the maximum” or “maximize the minimum”
- A monotonic yes/no check is easy to write
- A huge answer range, up to 10⁹
Avoid it when
- The check isn’t monotonic
- A formula or a greedy pass gives the answer directly
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Binary search over a range of size m | O(n log m) | O(1) |
| Try every answer | O(n × m) | O(1) |
| One feasibility check | O(n) | O(1) |
Often confused with: plain binary search - it looks for a value in sorted data; this searches the space of answers.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- The answer is often bounded by max(nums) or sum(nums)
- An O(n) check gives O(n log range) overall
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Using lo <= hi together with hi = mid - an infinite loop
- Starting lo at 0 - the check divides by zero
- Testing feasibility in the wrong direction
Edge cases to test
- h equals the number of piles - the answer is max(piles)
- A single pile
- Very large values - keep the check in integer maths
Knowledge check
Quick check to lock in the intuition.
What must be true for binary search on the answer to work?
Practice
Apply what you just watched on real interview problems.