Divide Chocolate solution explained

Divide Chocolate is solved by binary searching on the answer: guess a minimum sweetness, then walk the bar once and greedily close a piece as soon as its total reaches the guess. If that greedy walk produces at least k + 1 pieces the guess is achievable, so you search for the largest achievable guess in O(n log S) time and O(1) extra space, where S is the total sweetness.

By Published 9 min read

The problem in plain words

A chocolate bar is a row of segments, and each segment has a sweetness number. You are sharing it with k friends, so you make exactly k cuts and end up with k + 1 pieces. Every piece must be a run of neighboring segments; you cannot rearrange the bar. Being generous, you hand the friends the better pieces and keep the one with the lowest total for yourself. Choose the cuts so that this worst piece is as sweet as it can be, and return its total.

Examples written for this page
SweetnessFriends (k)Best resultOne set of cuts that achieves it
[3, 1, 4, 1, 5, 9, 2]26[3, 1, 4] [1, 5] [9, 2] gives 8, 6, 11
[6, 2, 2, 6]24[6] [2, 2] [6] gives 6, 4, 6
[1, 1, 1, 10]13[1, 1, 1] [10]: the big segment cannot lift the small side
[5, 5, 5, 5]35Every segment is its own piece
[2, 7, 1, 8]018No friends, no cuts, you keep the whole bar
Examples written for this page. Scroll sideways on a small screen.

Clarify a few things before coding. Are all sweetness values positive? (The greedy check depends on it.) Are there always at least k + 1 segments? Can totals overflow a 32-bit int in your language?

Why it shows up in interviews

The prompt sounds like a partition problem, and many candidates start drawing dynamic programming tables. The interviewer is waiting to see whether you notice a simpler structure: if you can guarantee every piece at least x, you can also guarantee every piece at least x minus 1. Feasibility is monotone in the guess, and monotone yes or no questions are what binary search is for. The second signal is the check itself, a single greedy pass that you should be able to justify, not just write.

Slow approach: try every set of cuts

There are n minus 1 gaps between segments and you pick k of them. For each choice, add up each piece, take the smallest, and keep the best smallest value seen. That is correct and easy to say, but the number of choices is n minus 1 choose k, which explodes once n reaches a few dozen. Mention it, give its cost, and move on.

from itertools import combinations

def best_smallest_piece_slow(sweet, friends):
    n = len(sweet)
    best = 0
    for cuts in combinations(range(1, n), friends):
        bounds = (0,) + cuts + (n,)
        smallest = min(sum(sweet[a:b]) for a, b in zip(bounds, bounds[1:]))
        best = max(best, smallest)
    return best
Brute force over cut positions, exponential in practice.

A dynamic programming table over (position, pieces left) cuts this to roughly O(n² k), still too slow for long bars. One sentence on it is enough.

Main approach: binary search on the answer

Flip the question. Instead of asking for the best minimum directly, ask: given a floor x, can I cut the bar so that every one of the k + 1 pieces has total at least x? To answer, walk left to right with a running sum. The moment the running sum reaches x, close the piece, count it and reset. At the end, if you closed at least k + 1 pieces, the answer is yes. Any leftover tail that never reached x is merged into the last closed piece, which only makes that piece sweeter.

Why is closing early safe? Closing a piece the first time it reaches x leaves the most chocolate for the pieces after it. Any other valid cutting closes its first piece at the same point or later, so the greedy walk is never behind it. If greedy closes more than k + 1 pieces, merge extras into neighbors; merging only raises totals, so the floor still holds.

Now pick the search range. The lowest floor that always works is the smallest single segment, because cutting between every segment would satisfy it and there are at least k + 1 segments. The highest floor that could work is total divided by k + 1, rounded down, since k + 1 pieces cannot all exceed the average. Search for the largest x in that range that passes the check.

def best_smallest_piece(sweet, friends):
    pieces = friends + 1

    def can_reach(floor):
        closed, running = 0, 0
        for value in sweet:
            running += value
            if running >= floor:
                closed += 1
                running = 0
        return closed >= pieces

    lo, hi = min(sweet), sum(sweet) // pieces
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if can_reach(mid):
            lo = mid
        else:
            hi = mid - 1
    return lo
Python: binary search on the floor, greedy check, O(n log S) time.
function bestSmallestPiece(sweet, friends) {
  const pieces = friends + 1;
  const canReach = (floor) => {
    let closed = 0;
    let running = 0;
    for (const value of sweet) {
      running += value;
      if (running >= floor) {
        closed += 1;
        running = 0;
      }
    }
    return closed >= pieces;
  };
  let lo = sweet.reduce((a, b) => Math.min(a, b));
  let hi = Math.floor(sweet.reduce((a, b) => a + b, 0) / pieces);
  while (lo < hi) {
    const mid = Math.floor((lo + hi + 1) / 2);
    if (canReach(mid)) lo = mid;
    else hi = mid - 1;
  }
  return lo;
}
JavaScript: the same search, with reduce instead of spreading a large array into Math.min.

Notice the mid calculation rounds up. The loop keeps lo as a known good value and moves it to mid on success. If mid rounded down, then with lo and hi one apart mid would equal lo, a success would leave lo unchanged and the loop would spin forever. Rounding up is the standard fix whenever you search for the last true value.

A short trace

Take [3, 1, 4, 1, 5, 9, 2] with two friends, so three pieces. The total is 25, so hi is 8 and lo is 1. Try 5: the walk closes [3, 1, 4], then [1, 5], then [9], and the tail [2] joins the last piece. Three pieces, so 5 works and lo becomes 5. Try 7: it closes [3, 1, 4] and [1, 5, 9], then [2] is short, so only two pieces; hi becomes 6. Try 6: [3, 1, 4], [1, 5] and [9] close three pieces, and [2] rides along with the last. lo and hi meet at 6, which matches the table.

Complexity

Cost of each approach for n segments with total sweetness S
ApproachTimeExtra memoryNotes
All cut combinationsO(C(n - 1, k) · n)O(k)Only for tiny bars
DP over position and piecesAbout O(n² k)O(n k)Correct but slow for large inputs
Binary search plus greedyO(n log S)O(1)The expected answer
Cost of each approach for n segments with total sweetness S. Scroll sideways on a small screen.

The log factor is over the value range, not the array length. With totals up to around a billion that is about 30 passes over the array, which is why this runs comfortably on large inputs.

Edge cases worth testing

  • k equal to 0: no cuts, the answer is the whole sum. The range collapses to a single value and the loop does not run.
  • k + 1 equal to the number of segments: every segment is its own piece, so the answer is the smallest segment.
  • One very large segment next to small ones, like [1, 1, 1, 10] with one friend. The answer is 3, not 10, because the small side caps it.
  • All segments equal to v: the answer is v times n // (k + 1), because the shortest piece gets that many segments.
  • Large totals in fixed-width languages: use 64-bit sums.

Common mistakes

  • Counting k pieces instead of k + 1. You are one of the people eating, so the bar splits k + 1 ways.
  • Using lo + hi over 2 with lo = mid, which loops forever when the two bounds are adjacent.
  • Treating a leftover tail as a failure. A tail that never reaches the floor simply joins the previous piece.
  • Assuming the greedy check still works with zero or negative sweetness. It relies on running sums only growing; with negatives you need a different method, so say so if asked.
  • Spreading a huge array into Math.min in JavaScript, which can throw a range error on very long inputs.

Saying it out loud

Fictional example

How a candidate might narrate the key step
Candidate
Trying every set of cuts is exponential, so I want a yes or no question I can binary search. If I can give every piece at least x, I can also give at least x minus 1, so feasibility only flips once.
Candidate
To test a floor, I sweep left to right and close a piece the moment its sum reaches the floor. Closing early leaves the most for later pieces, so if greedy cannot make k + 1 pieces, nothing can.
Candidate
The range is from the smallest segment to the total over k + 1. Each check is linear, so the whole thing is n times log of the total.

Where this pattern goes next

The same guess and check skeleton handles Maximum Candies Allocated to K Children, where the check is a sum of integer divisions, and Minimum Time to Complete Trips, which searches for the smallest feasible time instead of the largest feasible floor. For a broader refresher on searching, sorting and greedy proofs, see the algorithm interview questions guide.

Practice with Natively

When you rehearse a problem like this, Natively can read it from a screenshot and suggest a direction, which is most useful after you have tried the monotone argument on your own and want to compare notes. It also keeps a transcript of a mock session on your computer, so you can check afterward whether you explained the search range and the round-up midpoint clearly. See how an AI interview assistant fits into practice on Mac and Windows.

Questions people ask

What is the best approach for Divide Chocolate?

Binary search on the answer. Guess a minimum sweetness, sweep the bar once closing a piece whenever its running sum reaches the guess, and check whether you got at least k + 1 pieces. Keep the largest guess that passes.

Why does the greedy check work?

Closing a piece as soon as it reaches the floor leaves the most sweetness for the remaining pieces, so no other cutting can produce more pieces that meet the same floor.

What is the time complexity of the Divide Chocolate solution?

O(n log S), where n is the number of segments and S is the total sweetness. Each guess costs one linear pass and the search takes about log S guesses. Extra memory is O(1).

Why does the midpoint round up in this binary search?

The loop moves lo to mid on success. Rounding down would make mid equal lo when the bounds are adjacent, and the loop would never finish. Rounding up guarantees progress when searching for the last value that works.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP