Skip to the solution
MediumDSA9 min read

What is binary search on the answer?

610 views

The problem

Question presented to candidate: "What does "binary search on the answer" mean? Show me how you would use it to find the minimum eating speed in the Koko bananas problem, and code it in Python."

What a strong answer should cover:

  • Searching the range of possible answers, not an array, with a yes/no feasible(x) check.
  • The requirement: the check is monotonic, with a one-sentence reason (faster speed never needs more hours).
  • Correct bounds (lo = 1, hi = max pile for Koko) and the right template: "first true" with hi = mid, or "last true" with a rounded-up midpoint.
  • Complexity O(n log M) for Koko, versus O(n ร— M) for trying every speed.
  • Python specifics: exact ceiling division with (p + k - 1) // k, and that big integers make overflow a non-issue (so the focus is on the template).
  • Recognises other instances: ship within D days, split array largest sum, maximise the minimum distance, integer square root.

Clarifying questions expected:

  • What are the limits on the pile sizes and the number of hours?
  • Is there always a valid answer (at least one hour per pile)?

Code / implementation expected: Yes โ€” a Python feasible helper plus the binary search loop over the answer range.

  • binary-search
  • search-space

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonKoko eating bananas: binary vs linear search over speeds
PythonShip within D days and integer square root
PythonReal-valued answers: halving a fixed number of times

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 79 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the node where a linked list cycle begins?

Continue