{"id":"koko-eating-bananas","title":"Koko Eating Bananas","difficulty":"medium","patterns":["binary-search"],"primaryConcept":"binary-search-modified","concepts":["binary-search-modified"],"problemForm":"core","companies":[],"category":"searching-sorting","compareMode":"exact","description":"Koko has `piles` of bananas and exactly `h` hours to finish them. Each hour she chooses one pile and eats up to `k` bananas from it. If a pile has fewer than `k` bananas, she finishes that pile and does not eat from another pile during the same hour.\n\nReturn the minimum integer eating speed `k` that lets Koko finish all piles within `h` hours.\n\nRequirements:\n- `piles` is non-empty and contains positive integers.\n- `h` is at least the number of piles.\n- Return the smallest feasible speed, not just any feasible speed.","examples":[{"input":"piles = [3,6,7,11], h = 8","output":"4","explanation":"At speed 4, the piles take 1 + 2 + 2 + 3 = 8 hours. Speeds 1, 2, and 3 take too long."},{"input":"piles = [30,11,23,4,20], h = 5","output":"30","explanation":"With only one hour per pile, Koko must be able to finish the largest pile in one hour."},{"input":"piles = [30,11,23,4,20], h = 6","output":"23","explanation":"Speed 23 finishes in 6 hours, and every smaller speed takes more than 6 hours."}],"constraints":[{"id":"1-len-piles-10-4","text":"1 <= len(piles) <= 10^4","check":{"kind":"sizeRange","target":"piles","measure":"arrayLength","min":1,"max":10000}},{"id":"1-piles-i-10-9","text":"1 <= piles[i] <= 10^9","check":{"kind":"valueRange","target":"piles","selector":"arrayItems","min":1,"max":1000000000}},{"id":"len-piles-h-10-9","text":"len(piles) <= h <= 10^9"}],"starterCode":"class Solution:\n    def minEatingSpeed(self, piles: list[int], h: int) -> int:\n        # Your code here\n        pass","functionName":"minEatingSpeed","testCases":[{"id":"1","input":{"piles":[3,6,7,11],"h":8},"expected":4,"description":"Standard case with an interior minimum speed."},{"id":"2","input":{"piles":[30,11,23,4,20],"h":5},"expected":30,"description":"Only one hour is available per pile."},{"id":"3","input":{"piles":[30,11,23,4,20],"h":6},"expected":23,"description":"One extra hour lowers the answer."},{"id":"4","input":{"piles":[1,2,3],"h":5},"expected":2,"description":"Small imported seed case."},{"id":"5","input":{"piles":[1],"h":1},"expected":1,"description":"Single pile and one hour."},{"id":"h1","input":{"piles":[9,9,9],"h":3},"expected":9,"description":"Exactly one hour per pile forces the maximum pile size."},{"id":"h2","input":{"piles":[9,9,9],"h":6},"expected":5,"description":"A small increase in hours lowers the minimum speed."},{"id":"h3","input":{"piles":[30,11,23,4,20],"h":7},"expected":20,"description":"The classic sample with one more hour."},{"id":"h4","input":{"piles":[1,1,1,1,1],"h":5},"expected":1,"description":"Five tiny piles still need at least one banana per hour."},{"id":"h5","input":{"piles":[2,8,8],"h":4},"expected":8,"description":"The speed must be high enough to keep total hours within the budget."},{"id":"topup-1","input":{"piles":[1000000000],"h":2},"expected":500000000,"description":"Top-up case 1: a single very large pile requires ceiling division at the upper constraint scale."},{"id":"topup-2","input":{"piles":[19,23,17,11],"h":10},"expected":9,"description":"Top-up case 2: several medium piles require binary search to find the minimum feasible speed."}],"hints":[{"level":1,"content":"Try asking whether a proposed speed is fast enough. If a speed works, every larger speed also works.","revealPattern":false},{"level":2,"content":"Binary search over the answer range from 1 to max(piles).","revealPattern":true},{"level":3,"content":"For a speed `mid`, each pile takes `ceil(pile / mid)` hours, which can be computed as `(pile + mid - 1) // mid`.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which way of finding the slowest speed that fits still works when a pile holds a billion bananas?","decisionPrompt":"Compare how many speeds each one has to test.","approaches":[{"id":"linear-speed-scan","name":"Try every speed from 1 upward","summary":"Add up the hours for speed 1, then 2, then 3, and return the first speed that fits.","decisionReason":"It returns the right speed, but it tests every speed below the answer, and the answer can be as large as the largest pile, up to 1,000,000,000.","complexity":{"time":"O(n * max(piles))","space":"O(1)"},"tradeoffs":["Needs nothing beyond a running total of hours.","The number of tests grows with the size of the answer."],"isOptimal":false},{"id":"binary-search-answer","name":"Test the middle speed and halve the range","summary":"Keep the slowest and fastest speeds that could still be the answer, test the speed halfway between them, and drop the half that the test rules out.","decisionReason":"A speed that fits makes every faster speed fit, so each test rules out half of the range from 1 to the largest pile. A billion speeds take about 30 tests.","complexity":{"time":"O(n log max(piles))","space":"O(1)"},"tradeoffs":["Keeps two bounds and adds up the hours again for each middle speed.","Relies on the hours never rising as the speed rises."],"isOptimal":true}]},"codingCheckpoints":[{"id":"loop-window","title":"Loop while more than one speed is possible","description":"Set the lower and upper bounds on the answer, 1 and the largest pile, then repeat while the lower bound is below the upper one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"maintains_search_window","scope":"while-condition","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Starting the lower bound at 0, which lets the search test speed 0 and divide by zero","Looping while the bounds are equal as well: with one speed left the midpoint is that speed, it fits, and the range never shrinks"],"hint":"When the two bounds are equal, one speed is left and it is the answer, so the loop has nothing more to test.","semanticSpec":{"intent":"Maintain a binary-search window over candidate speeds.","doneWhen":"This step is done when the search continues while the lower speed is below the upper speed.","shouldFailWhen":"This step should fail if the loop does not use the speed bounds or if it is unreachable.","roles":["left speed","right speed","candidate window"],"mustProve":["The loop guard compares the active speed bounds.","The window remains the control structure for the search."],"mustNotAccept":["A fixed-count loop that ignores the bounds.","A loop over piles instead of candidate speeds."],"equivalentVariants":["Use `while left < right`.","Use equivalent bound names with a strict candidate-window guard."],"proofSnippets":[{"id":"py-koko-loop-window","language":"python","code":"class Solution:\n    def minEatingSpeed(self, piles: list[int], h: int) -> int:\n        left, right = 1, max(piles)\n        while left < right:\n            return left\n        return left"}]}},{"id":"mid-speed","title":"Pick the speed halfway between the bounds","description":"Inside the loop, compute the speed to test from the two bounds, rounded down.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"computes_midpoint_from_bounds","scope":"calculate-mid","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Rounding the midpoint up: with two speeds left it picks the faster one, which fits, so the range never shrinks","Computing it once before the loop, so every pass tests the same speed"],"hint":"It is computed again on every pass, from the bounds as they stand at that moment.","semanticSpec":{"intent":"Compute the candidate speed from the active binary-search bounds.","doneWhen":"This step is done when each iteration computes a midpoint speed from left and right.","shouldFailWhen":"This step should fail if mid is constant, derived from unrelated values, or computed before bounds are initialized.","roles":["left speed","right speed","midpoint speed"],"mustProve":["The midpoint is assigned inside the search loop.","The midpoint depends on both search bounds."],"mustNotAccept":["Using a fixed candidate speed.","Computing mid from only one bound.","Linear speed scanning."],"equivalentVariants":["Use `(left + right) // 2`.","Use an equivalent overflow-safe midpoint form."],"proofSnippets":[{"id":"py-koko-mid-speed","language":"python","code":"class Solution:\n    def minEatingSpeed(self, piles: list[int], h: int) -> int:\n        left, right = 1, max(piles)\n        while left < right:\n            mid = (left + right) // 2\n            return mid\n        return left"}]}},{"id":"hours-signal","title":"Add up the hours at that speed and compare with `h`","description":"For the speed being tested, total the hours over every pile, rounding each pile up to a whole hour. Then test whether that total is within `h`.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"evaluates_midpoint_feasibility_signal","scope":"evaluate-feasibility","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Dividing the total number of bananas by the speed, as if leftover speed carried from one pile to the next","Rounding each pile down, which counts a pile of 7 at speed 4 as one hour"],"hint":"A pile takes its size divided by the speed, rounded up. The speed fits when the total is at most `h`.","semanticSpec":{"intent":"Derive a feasibility signal from the candidate speed.","doneWhen":"This step is done when the code computes total hours from all piles using the midpoint speed.","shouldFailWhen":"This step should fail if feasibility is checked against the midpoint directly or if the hours calculation is unrelated to piles.","roles":["midpoint speed","piles","required hours","hour budget"],"mustProve":["The feasibility value is derived from the midpoint speed.","The calculation aggregates the required hours for the piles.","The budget comparison uses that derived hours signal."],"mustNotAccept":["Comparing mid directly to h without computing pile hours.","Using only one pile as the feasibility signal.","Ignoring the ceiling division behavior."],"equivalentVariants":["Use `sum((pile + mid - 1) // mid for pile in piles)`.","Use an equivalent loop that accumulates ceiling divisions for each pile."],"proofSnippets":[{"id":"py-koko-hours-signal","language":"python","code":"class Solution:\n    def minEatingSpeed(self, piles: list[int], h: int) -> int:\n        left, right = 1, max(piles)\n        while left < right:\n            mid = (left + right) // 2\n            hours = sum((pile + mid - 1) // mid for pile in piles)\n            if hours <= h:\n                return mid\n            return right\n        return left"}]}},{"id":"adjust-bounds","title":"Move one bound after each test","description":"If the tested speed fits within `h` hours, bring the upper bound down to it. If it is too slow, move the lower bound one past it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"narrows_bounds_around_midpoint","scope":"adjust-answer-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Moving the upper bound to one below a speed that fits, which can remove the answer","Treating a total equal to `h` as too slow, when finishing in the last hour is in time"],"hint":"On the example with 8 hours, speed 5 fit, so the upper bound came down to 5. Speed 3 was too slow, so the lower bound moved up to 4.","semanticSpec":{"intent":"Narrow the answer range according to midpoint feasibility.","doneWhen":"This step is done when feasible speeds move the upper bound to mid and infeasible speeds move the lower bound to mid + 1.","shouldFailWhen":"This step should fail if feasible midpoints are discarded or if the branch direction is reversed.","roles":["feasibility signal","left speed","right speed","midpoint speed"],"mustProve":["The feasibility branch controls both bound updates.","A feasible midpoint remains in the candidate range.","An infeasible midpoint is excluded by advancing the lower bound."],"mustNotAccept":["Using `right = mid - 1` for a feasible midpoint.","Using `left = mid` after an infeasible midpoint.","Updating bounds without the hours feasibility signal."],"equivalentVariants":["Use `if hours <= h: right = mid; else: left = mid + 1`.","Use an equivalent predicate where the true/false branches preserve the same candidate range."],"proofSnippets":[{"id":"py-koko-adjust-bounds","language":"python","code":"class Solution:\n    def minEatingSpeed(self, piles: list[int], h: int) -> int:\n        left, right = 1, max(piles)\n        while left < right:\n            mid = (left + right) // 2\n            hours = sum((pile + mid - 1) // mid for pile in piles)\n            if hours <= h:\n                right = mid\n            else:\n                left = mid + 1\n        return 0"}]}},{"id":"return-speed","title":"Return the speed the bounds meet on","description":"After the loop the two bounds are equal. Return that speed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"binary-search","fact":"returns_search_boundary","scope":"return-boundary","readMode":"binary-search-value-query-v1"}]},"commonMistakes":["Returning the last speed tested, which may be one that was too slow","Returning from inside the loop the first time a speed fits, before the slower speeds are ruled out"],"hint":"It may never have been tested. It is still the answer, because the range always contains the slowest speed that fits.","semanticSpec":{"intent":"Return the collapsed answer boundary after the monotone feasibility search.","doneWhen":"This step is done when the function returns the remaining speed boundary after all narrowing is complete.","shouldFailWhen":"This step should fail if the function returns a stale midpoint, returns inside the loop, or returns a non-boundary value.","roles":["collapsed speed boundary","minimum feasible speed","return value"],"mustProve":["Both feasible and infeasible branch updates are present.","The return happens after the loop.","The returned value is the final search boundary."],"mustNotAccept":["Returning `mid` after the loop.","Returning the hours count.","Returning before the search window collapses."],"equivalentVariants":["Return `left` after the loop.","Return `right` after the loop when the algorithm maintains `left == right` at exit."],"proofSnippets":[{"id":"py-koko-return-speed","language":"python","code":"class Solution:\n    def minEatingSpeed(self, piles: list[int], h: int) -> int:\n        left, right = 1, max(piles)\n        while left < right:\n            mid = (left + right) // 2\n            hours = sum((pile + mid - 1) // mid for pile in piles)\n            if hours <= h:\n                right = mid\n            else:\n                left = mid + 1\n        return left"}]}}],"version":2,"slides":[{"id":"opener","kind":"info","title":"Find the slowest speed that still finishes every pile","workspacePanel":"problem","body":["Koko has several piles of bananas and a fixed number of hours to eat them all. She picks one eating speed, a whole number of bananas per hour, and keeps it from start to finish.","Each hour she eats from one pile. If that pile holds fewer bananas than her speed, she finishes it and waits for the next hour before starting another.","She is always given at least one hour per pile. Return the slowest speed that still gets every pile eaten in time.","Drawn here are four piles and 8 hours to eat them in."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"example","state":{"arrays":[{"name":"piles","values":[3,6,7,11]}],"h":8}}]}},{"id":"pile-hours","kind":"case-probe","title":"At speed 4, how many hours does the pile of 7 take?","workspacePanel":"visualizer","options":[{"id":"two-hours","label":"2 hours","rationale":"She eats 4 in the first hour and the last 3 in the second. Every pile works this way: its size divided by the speed, rounded up to a whole hour.","isCorrect":true},{"id":"one-and-three-quarters","label":"1.75 hours","rationale":"7 / 4 is 1.75, but the rest of that second hour is lost. She does not start another pile until the next hour.","isCorrect":false},{"id":"one-hour","label":"1 hour","rationale":"One hour at speed 4 removes 4 bananas, and 3 are still in the pile.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pile-of-seven","state":{"arrays":[{"name":"piles","values":[3,6,7,11],"current":2}],"speed":4}}]}},{"id":"speed-four","kind":"case-probe","title":"Does speed 4 finish all four piles within 8 hours?","workspacePanel":"visualizer","options":[{"id":"exactly-eight","label":"Yes, it takes exactly 8 hours","rationale":"1 + 2 + 2 + 3 = 8. Finishing in the last hour still counts as in time.","isCorrect":true},{"id":"needs-fewer","label":"No, it would have to take fewer than 8","rationale":"Koko has 8 full hours. A speed is too slow only when it needs a 9th.","isCorrect":false},{"id":"hour-to-spare","label":"Yes, with an hour to spare","rationale":"27 bananas at 4 an hour would take under 7 hours if leftover speed carried over to the next pile. It does not, and the piles take 8 between them.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"speed-four-hours","state":{"rows":[{"label":"piles","values":[3,6,7,11]},{"label":"hours per pile","values":[1,2,2,3]}],"speed":4,"h":8}}]}},{"id":"brute-force","kind":"code-trace","title":"Try every speed, slowest first","summary":"The first speed that fits is the answer, because every slower speed has already been tried and was too slow.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"for speed in range(1, max(piles) + 1):\n    hours = 0\n    for pile in piles:\n        hours += (pile + speed - 1) // speed\n    if hours <= h:\n        return speed","steps":[{"id":"scan-1","title":"Speed 1 needs 27 hours","codeLine":5,"summary":"At one banana an hour every banana costs an hour: 3 + 6 + 7 + 11 = 27, and Koko has 8.","state":{"arrays":[{"name":"piles","values":[3,6,7,11]},{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11],"current":0}],"hours":27,"h":8}},{"id":"scan-2","title":"Speed 2 needs 15 hours","codeLine":5,"summary":"2 + 3 + 4 + 6 = 15, still too slow.","state":{"arrays":[{"name":"piles","values":[3,6,7,11]},{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11],"current":1}],"hours":15,"h":8}},{"id":"scan-3-rounding","title":"Each pile's hours are rounded up","codeLine":4,"summary":"For the pile of 11 at speed 3, the loop adds (11 + 3 - 1) / 3 with the remainder dropped: 13 / 3 gives 4. Plain 11 / 3 would have given 3 and left the last 2 bananas uneaten.","state":{"arrays":[{"name":"piles","values":[3,6,7,11],"current":3},{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11],"current":2}],"h":8}},{"id":"scan-3","title":"Speed 3 needs 10 hours","codeLine":5,"summary":"1 + 2 + 3 + 4 = 10, which is 2 hours too many.","state":{"arrays":[{"name":"piles","values":[3,6,7,11]},{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11],"current":2}],"hours":10,"h":8}},{"id":"scan-4","title":"Speed 4 needs 8 hours","codeLine":6,"summary":"1 + 2 + 2 + 3 = 8 fits, so the loop returns 4.","state":{"arrays":[{"name":"piles","values":[3,6,7,11]},{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11],"current":3}],"hours":8,"h":8}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"for (let speed = 1; speed < (Math.max(...piles) + 1); speed++) {\n    let hours = 0;\n    for (const pile of piles) {\n        hours += Math.floor(((pile + speed) - 1) / speed);\n    }\n    if (hours <= h) {\n        return speed;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"for (let speed = 1; speed < (Math.max(...piles) + 1); speed++) {\n    let hours = 0;\n    for (const pile of piles) {\n        hours += Math.floor(((pile + speed) - 1) / speed);\n    }\n    if (hours <= h) {\n        return speed;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"for (int speed = 1; speed < (Collections.max(piles) + 1); speed++) {\n    int hours = 0;\n    for (Integer pile : piles) {\n        hours += Math.floorDiv(((pile + speed) - 1), speed);\n    }\n    if (hours <= h) {\n        return speed;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"for (int speed = 1; speed < piles.Max() + 1; speed++) {\n    int hours = 0;\n    foreach (int pile in piles) {\n        hours += (pile + speed - 1) / speed;\n    }\n    if (hours <= h) {\n        return speed;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"for (int speed = 1; speed < (*max_element(piles.begin(), piles.end()) + 1); speed++) {\n    int hours = 0;\n    for (int pile : piles) {\n        hours += (((pile + speed) - 1) / speed);\n    }\n    if (hours <= h) {\n        return speed;\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":6,"6":7},"statementBundles":{"4":{"startLine":4,"endLine":5},"6":{"startLine":7,"endLine":9}}}}}},{"id":"upper-bound-probe","kind":"case-probe","title":"The loop never tries a speed above 11, the largest pile. Why is that safe?","workspacePanel":"visualizer","options":[{"id":"one-hour-each","label":"At speed 11 every pile takes one hour, and Koko always has an hour per pile","rationale":"Four piles take 4 hours at speed 11. No pile can take less than an hour, so a faster speed gains nothing. So the answer is always between 1 and the largest pile, and the largest pile always fits.","isCorrect":true},{"id":"speed-cap","label":"Koko cannot eat more than 11 bananas in an hour","rationale":"Nothing limits her speed. A faster one is allowed, but it still spends a full hour on each pile.","isCorrect":false},{"id":"faster-costs-more","label":"A speed above 11 would need more hours","rationale":"Speed 12 also spends one hour on each pile, the same 4 in total.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"speed-eleven-hours","state":{"rows":[{"label":"piles","values":[3,6,7,11]},{"label":"hours per pile","values":[1,1,1,1]}],"speed":11,"h":8}}]}},{"id":"cost-probe","kind":"case-probe","title":"How many speeds does the loop try on these piles?","summary":"The last pile now holds 1,000,000,000 bananas, and Koko has 4 hours.","workspacePanel":"visualizer","options":[{"id":"four","label":"4","rationale":"Speed 4 fit the first piles. Here it would spend 250,000,000 hours on the last pile alone.","isCorrect":false},{"id":"quarter-billion","label":"250,000,000","rationale":"A billion bananas spread over all 4 hours is 250,000,000 an hour, but three of those hours belong to the other piles.","isCorrect":false},{"id":"billion","label":"1,000,000,000","rationale":"Four piles in 4 hours leaves one hour for the last pile, so nothing slower than 1,000,000,000 fits. The loop tries 999,999,999 speeds that are too slow before it gets there.","isCorrect":true}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"billion-pile","state":{"arrays":[{"name":"piles","values":[3,6,7,"10⁹"]}],"h":4}}]}},{"id":"monotonicity-probe","kind":"case-probe","title":"Back on the first piles, the loop stopped at speed 4. What do you already know about speeds 5 through 11?","workspacePanel":"visualizer","options":[{"id":"all-fit","label":"Each of them fits within 8 hours","rationale":"A faster speed never makes any pile take longer, so none of their totals can pass speed 4's 8 hours.","isCorrect":true},{"id":"unknown","label":"Nothing, until each one is tried","rationale":"Their exact totals are unknown, but each is at most 8, because eating faster cannot add hours to any pile.","isCorrect":false},{"id":"some-fail","label":"Some of them may need more than 8 hours","rationale":"For a total to rise, some pile would have to take longer at a higher speed, and none can.","isCorrect":false}],"answer":"Speeds 5 through 11 need 8, 6, 5, 5, 5, 5 and 4 hours.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"scan-results","state":{"arrays":[{"name":"piles","values":[3,6,7,11]}],"rows":[{"label":"speed","values":[1,2,3,4,5,6,7,8,9,10,11]},{"label":"hours","values":[27,15,10,8,"","","","","","",""]}],"h":8}}]}},{"id":"first-test","kind":"case-probe","title":"With nothing tried yet, which first test rules out the most speeds whichever way it turns out?","workspacePanel":"visualizer","options":[{"id":"speed-one","label":"Speed 1","rationale":"If speed 1 is too slow, that rules out speed 1 alone. The loop started the same way.","isCorrect":false},{"id":"speed-six","label":"Speed 6","rationale":"If 6 fits, 7 through 11 fit too, so none of them is the slowest. If 6 is too slow, 1 through 5 are slower still and fail with it. Either way at least five speeds are gone.","isCorrect":true},{"id":"speed-eleven","label":"Speed 11","rationale":"Speed 11 always fits, so trying it rules out nothing.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"untested-speeds","state":{"arrays":[{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11]}],"h":8}}]}},{"id":"window-invariant","kind":"case-probe","title":"Speed 6 needs 6 hours, so it fits. With only that test done, which speeds could still be the answer?","workspacePanel":"visualizer","options":[{"id":"one-to-five","label":"1 through 5","rationale":"Only 6 has been tested so far. Until a slower speed is shown to fit, 6 itself could be the answer.","isCorrect":false},{"id":"one-to-six","label":"1 through 6","rationale":"6 fits, so no faster speed can be the slowest that fits. 6 itself still can, and only a slower speed that also fits could replace it.","isCorrect":true},{"id":"seven-to-eleven","label":"7 through 11","rationale":"They fit, but 6 is slower and fits too, so none of them is the slowest.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"speed-six-tested","state":{"arrays":[{"name":"speed","values":[1,2,3,4,5,6,7,8,9,10,11],"current":5}],"hours":6,"h":8}}]}},{"id":"bounds-and-midpoint","kind":"info","title":"Two bounds and the speed between them","workspacePanel":"visualizer","body":["Testing the middle of whatever is left, again and again, cuts the speeds still possible about in half each time. 11 speeds need at most 4 tests, and 1,000,000,000 speeds need at most 30.","The search keeps track of three speeds. Their usual names are `left`, `right` and `mid`."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bounds-start","title":"left and right are the slowest and fastest speeds still possible","summary":"Before any test, left is 1 and right is 11, the largest pile.","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":10,"h":8,"labels":{"nums":"speed"}}},{"id":"midpoint","title":"mid is the speed to test","summary":"mid is `(left + right) / 2`, rounded down. Here (1 + 11) / 2 is 6.","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":10,"mid":5,"h":8,"labels":{"nums":"speed"}}},{"id":"first-update","title":"Speed 6 fit, so right moves to 6","summary":"left stays at 1, and the speeds still possible are 1 through 6.","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":5,"hours":6,"h":8,"labels":{"nums":"speed"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Finish the search with 8 hours","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":5,"mid":2,"hours":10,"h":8,"labels":{"nums":"speed"}}},{"id":"speed-3","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":3,"right":5,"mid":4,"hours":8,"h":8,"labels":{"nums":"speed"}}},{"id":"speed-5","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":3,"right":4,"mid":3,"hours":8,"h":8,"labels":{"nums":"speed"}}},{"id":"speed-4","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":3,"right":3,"h":8,"labels":{"nums":"speed"}}}]},"beats":[{"id":"speed-3","title":"`mid` is 3, and speed 3 needs 10 hours. How do the bounds move?","options":[{"id":"left-to-four","label":"left moves to 4","rationale":"Speed 3 is too slow, and 1 and 2 are slower still. The slowest speed that could fit is 4.","isCorrect":true},{"id":"left-to-three","label":"left moves to 3","rationale":"Speed 3 just failed, so it cannot be the answer and has no place in the range.","isCorrect":false},{"id":"right-to-two","label":"right moves to 2","rationale":"That keeps 1 and 2, which are slower than a speed that already failed.","isCorrect":false}]},{"id":"speed-5","title":"Now `mid` is 5, and speed 5 needs exactly 8 hours. How do the bounds move?","options":[{"id":"right-to-five","label":"right moves to 5","rationale":"8 hours is within the 8 allowed, so speed 5 fits and stays as the fastest speed still possible.","isCorrect":true},{"id":"left-to-six","label":"left moves to 6","rationale":"That treats 8 hours as too slow. Koko has 8, so speed 5 fits.","isCorrect":false},{"id":"return-five","label":"Neither moves, and 5 is returned","rationale":"Speed 4 is still in the range and has not been tested. It may fit too.","isCorrect":false}]},{"id":"speed-4","title":"`mid` is 4, and speed 4 also needs 8 hours. What happens next?","options":[{"id":"meet-and-return","label":"right moves to 4, meets left, and 4 is returned","rationale":"One speed is left in the range, and the answer was never removed from it, so that speed is the answer. The loop runs only while left is below right, so it stops here.","isCorrect":true},{"id":"test-again","label":"right moves to 4, and speed 4 is tested again","rationale":"With left and right both at 4 there is nothing left to choose between, so no further test is needed.","isCorrect":false},{"id":"check-three","label":"right moves to 4, then speed 3 is tested to make sure","rationale":"Speed 3 has already been tested and was too slow. That is why left is 4.","isCorrect":false}]}]},{"id":"one-hour-probe","kind":"case-probe","title":"With only 4 hours, speeds 6, 9 and 10 are all too slow. What happens at 11?","workspacePanel":"visualizer","options":[{"id":"return-untested","label":"It is returned without being tested","rationale":"left and right are both 11, so the loop has ended. Speed 11 is the largest pile, which always fits.","isCorrect":true},{"id":"test-then-return","label":"It is tested, then returned","rationale":"A test only happens while left is below right, and here they are equal.","isCorrect":false},{"id":"no-answer","label":"It is too slow as well, so no speed fits","rationale":"At speed 11 each pile takes one hour, 4 in all, and Koko has 4.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"four-hours-end","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":10,"right":10,"h":4,"labels":{"nums":"speed"}}}]}},{"id":"wrong-update-intro","kind":"info","title":"The two bound updates are easy to write the same way","workspacePanel":"visualizer","body":["When the speed at mid is too slow, left moves to `mid + 1`, one past the speed that failed. The matching update for a speed that fits would move right to `mid - 1`. With 8 hours that version still returns 4.","The same piles with 6 hours tell the two versions apart."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"six-hours-start","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":10,"h":6,"labels":{"nums":"speed"}}}]}},{"id":"feasible-discard-pitfall","kind":"pitfall","title":"What goes wrong when right moves to `mid - 1`?","summary":"With 6 hours the answer should be speed 6: it fits, and speed 5 needs 8 hours.","workspacePanel":"trace","pitfall":"This version moves right to `mid - 1` after a speed fits.","whyItMatters":"Speed 6 was the answer, and the first update took it out of the range. Moving right to mid itself keeps it in, and the search then narrows down to 6.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"left = 1\nright = max(piles)\nwhile left < right:\n    mid = (left + right) // 2\n    hours = 0\n    for pile in piles:\n        hours += (pile + mid - 1) // mid\n    if hours <= h:\n        right = mid - 1\n    else:\n        left = mid + 1\nreturn left","steps":[{"id":"wrong-first-test","title":"The first test is speed 6","summary":"left is 1, right is 11, and mid is 6.","codeLine":4,"state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":10,"mid":5,"h":6,"labels":{"nums":"speed"}}},{"id":"wrong-fits","title":"Speed 6 fits","summary":"1 + 1 + 2 + 2 = 6 hours, exactly what Koko has.","codeLine":8,"state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":10,"mid":5,"hours":6,"h":6,"labels":{"nums":"speed"}}},{"id":"wrong-drop","title":"right moves to 5","summary":"The range is now 1 through 5, and speed 6 is outside it.","codeLine":9,"state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":4,"mid":5,"hours":6,"h":6,"labels":{"nums":"speed"}}},{"id":"wrong-speed-3","title":"Speed 3 is too slow","summary":"mid is 3. Speed 3 needs 10 hours, so left moves to 4.","codeLine":11,"state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":3,"right":4,"mid":2,"hours":10,"h":6,"labels":{"nums":"speed"}}},{"id":"wrong-speed-4","title":"Speed 4 is too slow as well","summary":"mid is 4. Speed 4 needs 8 hours, so left moves to 5 and meets right.","codeLine":11,"state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":4,"right":4,"mid":3,"hours":8,"h":6,"labels":{"nums":"speed"}}},{"id":"wrong-return","title":"Speed 5 is returned","summary":"Speed 5 needs 8 hours, and Koko has 6.","codeLine":12,"state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":4,"right":4,"hours":8,"h":6,"labels":{"nums":"speed"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let left = 1;\nlet right = Math.max(...piles);\nwhile (left < right) {\n    const mid = Math.floor((left + right) / 2);\n    let hours = 0;\n    for (const pile of piles) {\n        hours += Math.floor(((pile + mid) - 1) / mid);\n    }\n    if (hours <= h) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let left = 1;\nlet right = Math.max(...piles);\nwhile (left < right) {\n    const mid = Math.floor((left + right) / 2);\n    let hours = 0;\n    for (const pile of piles) {\n        hours += Math.floor(((pile + mid) - 1) / mid);\n    }\n    if (hours <= h) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int left = 1;\nint right = Collections.max(piles);\nwhile (left < right) {\n    int mid = Math.floorDiv((left + right), 2);\n    int hours = 0;\n    for (Integer pile : piles) {\n        hours += Math.floorDiv(((pile + mid) - 1), mid);\n    }\n    if (hours <= h) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int left = 1;\nint right = piles.Max();\nwhile (left < right) {\n    int mid = (left + right) / 2;\n    int hours = 0;\n    foreach (int pile in piles) {\n        hours += (pile + mid - 1) / mid;\n    }\n    if (hours <= h) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int left = 1;\nint right = *max_element(piles.begin(), piles.end());\nwhile (left < right) {\n    int mid = (left + right) / 2;\n    int hours = 0;\n    for (int pile : piles) {\n        hours += (((pile + mid) - 1) / mid);\n    }\n    if (hours <= h) {\n        right = mid - 1;\n    } else {\n        left = mid + 1;\n    }\n}\nreturn left;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":10,"10":11,"11":12,"12":15},"statementBundles":{"7":{"startLine":7,"endLine":8},"11":{"startLine":12,"endLine":14}}}}}},{"id":"ready-to-code","kind":"info","title":"That is how to find Koko's slowest speed. Now write the function.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["The function starts with left at 1 and right at the largest pile.","While left is below right, it tests mid, the speed halfway between them, rounded down. It adds up the hours every pile takes at that speed, each pile rounded up to a whole hour.","If the total is within the hours Koko has, right moves to mid. If not, left moves to `mid + 1`.","When left and right meet, the function returns that speed."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-state","state":{"nums":[1,2,3,4,5,6,7,8,9,10,11],"left":0,"right":10,"h":8,"labels":{"nums":"speed"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Write the speed search","workspacePanel":"code"},{"id":"complete","kind":"complete","title":"Searching Koko's speeds by halves","takeaways":[{"title":"Faster never takes longer","body":"Raising the speed cannot add hours to any pile. So every speed below the answer is too slow, and every speed from the answer up fits."},{"title":"A speed that fits survives its own test","body":"right moves to mid, because mid may be the answer. Only a speed that failed is stepped past, with left moving to `mid + 1`."},{"title":"The bounds meet on the answer","body":"When left equals right, one speed is left and it is returned without another test. Starting right on the largest pile guarantees that speed fits."},{"title":"About 30 tests where trying every speed can take a billion","body":"Each test adds up the hours for all n piles, and each test cuts the range from 1 to the largest pile m about in half. That is O(n log m) time against O(n × m) for trying every speed, with O(1) extra space for the two bounds, the midpoint and the hours total."}],"workspacePanel":"code"}],"slidesOrigin":"authored","progressRevision":"koko-eating-bananas-2026-11-20-speeds-by-halves"},"executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"piles","secondaryParam":"h","sizeMetric":"length","constraints":["positive"],"secondaryParams":{"h":{"strategy":"scale-with-primary"}}}}
