Interview conceptCoding & Algorithms

Binary Search On Answer

Asked of: Machine Learning Engineer

Last updated

Five-frame horizontal trace of 'binary search on answer' over a small integer value range, showing lo, mid, hi pointers, can(mid) true/false decisions, pointer updates, and final convergence with return value rule.

What's being tested

Binary search on answer: recognizing when the value you need is not directly searchable in an array, but a monotonic predicate over possible answers is. Interviewers are probing whether you can define bounds, implement can(x) correctly, prove monotonicity, and handle edge cases without off-by-one bugs.

Patterns & templates

  • Maximize feasible value — use while lo <= hi, move lo = mid + 1 when can(mid) is true; return hi.

  • Minimize feasible value — move hi = mid - 1 when can(mid) is true; return lo as the smallest valid answer.

  • Capacity partitioningcan(capacity) scans once, counting days/partitions; O(n log S) time, O(1) space, preserve input order.

  • Piece-count feasibilitysum(length // x) >= k is monotonic decreasing as x grows; avoid testing x = 0.

  • Value-space matrix search — count elements <= mid in O(n) from bottom-left/top-right; total O(n log range) time.

  • Integer-safe midpoint — compute mid = lo + (hi - lo) // 2; in Python overflow is irrelevant, but still communicate the habit.

Common pitfalls

Pitfall: Confusing searching indices with searching answer values; the answer may not appear as an array element.

Pitfall: Using the wrong return value after convergence; for “minimum feasible,” return lo, for “maximum feasible,” usually return hi.

Pitfall: Weak bounds cause bugs: shipping lower bound is max(weights), ribbon lower bound is 1, matrix bounds are min/max values.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Featured in interview prep guides

Practice questions

Related concepts

Binary Search On Answer — Tech Interview Concept | PracHub