Advanced Binary Search Patterns
Software Engineer path · lesson 48 of 99Visualize Binary Search on Answer Space through the Koko Eating Bananas (minimize-maximum) pattern. Watch how a feasibility predicate monotonically flips as the candidate answer grows, allowing binary search to locate the optimal value. The Learn tab covers maximize-minimum, rotated arrays, and other advanced variants.
Pile sizes 1–40. Koko eats up to k bananas from one pile per hour.
Fewer hours force a faster minimum speed. h is raised to the number of piles if it is lower.
Search speeds 1..11. "Finishes in 8h?" flips from no to yes exactly once, so binary search works on the answer.
- 1lo, hi = 1, max(piles)
- 2while lo < hi:
- 3 k = (lo + hi) // 2
- 4 hours = sum(ceil(p / k) for p in piles)
- 5 if hours <= h: hi = k # k works; try slower
- 6 else: lo = k + 1 # too slow
- 7return lo
- Speeds tried
- 0 / 4
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Binary search on the answer
Order the steps for Koko’s minimum eating speed.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
When should you use Binary Search on Answer?
Write the code
Koko Eating Bananas
function minEatingSpeed(piles, h) {
// Your code here
}The short version
Imagine finding the perfect meeting time for everyone. You don't check every minute - you guess a time, ask 'Is this too early or too late?', then adjust. Binary Search on Answer finds optimal values by repeatedly testing 'Is X achievable?'
In more depth
Binary Search on Answer Space
Instead of searching an array, you search a range of possible answers [lo, hi] to find the optimal value.
The Pattern:
Common Variants:
Key Gotchas:
lo < hi vs lo <= hi carefully)When to reach for this
- Problem asks for 'minimum maximum' or 'maximum minimum'
- Can verify if answer X is achievable in O(n)
- Answer space is bounded and monotonic
- Keywords: 'at least', 'at most', 'minimize the maximum'
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required