Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Binary search

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Binary search

Koko Eating Bananas

advancedlayer B6 · Binary search5 tests

There are piles.length piles of bananas and a guard who will be away for h hours. Koko picks an eating speed k bananas per hour. Each hour she picks one pile and eats up to k from it; if the pile has fewer than k left she eats it and still spends the whole hour on it. Return the smallest integer k that lets her finish every pile within h hours.

  • This is binary search on the answer: you are not searching the input array, you are searching the range of candidate speeds 1 .. max(piles)
  • The key property is monotonicity — if speed k works, every faster speed works too, so 'does k work?' splits the range into a false block then a true block
  • Hours needed at speed k is the sum of ceil(pile / k)
  • h is always at least piles.length

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen