Skip to solution
mediumDSA

What is binary search on the answer?

610 views
01

Understand the problem

Explain binary searching a value range.

binary-searchsearch-space
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

When the answer is monotonic — a candidate value either works or doesn't, with a clean threshold — you binary search over the value range instead of an array, using a feasibility check at each midpoint. Used for problems like Koko eating bananas or minimum ship capacity. O(log(range) × checkCost).

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

Koko eating bananas
Run Playground
def min_eating_speed(piles, hours):
    def hours_needed(speed):
        return sum((p + speed - 1) // speed for p in piles)   # ceil division
    lo, hi = 1, max(piles)
    while lo < hi:
        mid = (lo + hi) // 2
        if hours_needed(mid) <= hours:
            hi = mid             # feasible — try slower
        else:
            lo = mid + 1         # too slow — speed up
    return lo


# --- demo ---
print(min_eating_speed([3, 6, 7, 11], 8))        # 4
print(min_eating_speed([30, 11, 23, 4, 20], 5))  # 30
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 62 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.

Back to track