Capacity to Ship Packages Within D Days solution explained

Capacity to Ship Packages Within D Days asks for the smallest ship capacity that moves a list of parcels, in their given order, in at most D days, when each day the ship loads parcels from the front of the line until the next one would exceed its capacity. A larger capacity never needs more days, so binary search the capacity between the heaviest parcel and the total weight, and check each candidate with a one-pass simulation. That costs O(n log W) time for n parcels and total weight W, with O(1) extra space.

By Published 8 min read

The setup

A list of positive parcel weights waits at a dock in a fixed order. One ship makes one trip a day. Each day it takes parcels from the front of the line, in order, as long as the total stays within its capacity; the first parcel that would go over waits for the next day. Parcels cannot be split or reordered. Given a number of days D, return the smallest capacity that gets every parcel shipped within D days.

Parcel lists made up for this page
WeightsDaysAnswerLoads per day
[4, 8, 1, 7, 3, 2]312[4, 8] [1, 7, 3] [2]
[4, 8, 1, 7, 3, 2]213[4, 8, 1] [7, 3, 2]
[5, 5, 5, 5]210[5, 5] [5, 5]
[9, 1, 1]59Extra days do not help below the heaviest parcel
Parcel lists made up for this page. Scroll sideways on a small screen.

Why this question shows up

It is one of the cleanest introductions to binary search over an answer rather than over an array. The story hides the pattern a little, and the interviewer wants to see you notice that "smallest capacity such that something is possible" is a monotonic yes-or-no question. They also watch the details that make binary search code fragile: the starting bounds, the loop condition, which half keeps mid, and whether the check counts days correctly.

Checking one capacity

Before any search, write the function that answers "how many days does capacity c need?" Walk the weights, keep the current day's load, and when adding the next parcel would exceed c, count a new day and start its load at zero. Loading as much as possible each day is never worse than holding parcels back, since anything you leave behind only adds to later days.

def days_needed(weights, capacity):
    days, load = 1, 0
    for w in weights:
        if load + w > capacity:           # this package waits for tomorrow's ship
            days += 1
            load = 0
        load += w
    return days

def ship_within_days_linear(weights, days):
    capacity = max(weights)               # smaller than this and the heaviest package never ships
    while days_needed(weights, capacity) > days:
        capacity += 1
    return capacity
Days needed for a capacity, then the slow answer: try capacities upward from the heaviest parcel.

The linear scan is correct and a fair thing to say first. Its weak spot is the number of capacities it may try: up to the total weight minus the heaviest parcel, each costing a pass over the list. With weights in the hundreds and thousands of parcels, that is millions of passes.

Why binary search applies

Line the capacities up from small to large and mark each as good (fits within D days) or bad. A bigger ship never needs more days, so the marks look like bad, bad, ..., bad, good, good, ..., good. The answer is the first good one. Any time a problem has that shape, you can find the boundary with about log2 of the range checks instead of one check per value.

  1. Pick a provable lower bound and an upper bound that always workslo is the largest lower bound you can prove: the heaviest parcel, and also ceil(total / D), since D trips must carry the total. hi is the total, which ships everything in one day.
  2. Loop while the range has more than one valueWith while lo < hi, the loop ends when lo and hi meet, and that meeting point is the answer.
  3. Keep mid when it is goodIf mid fits, the answer is mid or smaller, so set hi = mid. If it does not fit, the answer is larger, so set lo = mid + 1.
  4. Round mid downWith lo < hi, mid = (lo + hi) // 2 is always below hi, so hi = mid shrinks the range and the loop cannot get stuck.
def ship_within_days(weights, days):
    total = sum(weights)
    lo = max(max(weights), (total + days - 1) // days)   # neither bound can be beaten
    hi = total                                           # one ship, one day, always enough
    while lo < hi:
        mid = (lo + hi) // 2
        if days_needed(weights, mid) <= days:
            hi = mid
        else:
            lo = mid + 1
    return lo
Binary search on capacity, reusing days_needed from above. O(n log W) time.

For [4, 8, 1, 7, 3, 2] in 3 days the total is 25, so lo = max(8, 9) = 9 and hi = 25. Capacity 17 needs 2 days: good, hi = 17. Capacity 13 needs 2: good, hi = 13. Capacity 11 needs 4: bad, lo = 12. Capacity 12 needs 3: good, hi = 12. The range is now a single value, 12.

function shipWithinDays(weights, days) {
  let lo = 0, hi = 0;
  for (const w of weights) {
    lo = Math.max(lo, w);
    hi += w;
  }
  const fits = (cap) => {
    let used = 1, load = 0;
    for (const w of weights) {
      if (load + w > cap) {
        used++;
        load = 0;
      }
      load += w;
    }
    return used <= days;
  };
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (fits(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}
JavaScript, with the check as a closure that returns true or false.

The JavaScript version starts lo at the heaviest parcel only. The ceil(total / D) bound is a small speedup, not a correctness requirement, and leaving it out keeps the code short. In languages with fixed-size integers, compute mid as lo + (hi - lo) / 2 and keep the total in a 64-bit type if it can be large.

Costs

n parcels, W = total weight, M = heaviest parcel
ApproachTimeExtra space
Try each capacity from M upwardO(n · (W - M))O(1)
Binary search on capacityO(n log W)O(1)
n parcels, W = total weight, M = heaviest parcel. Scroll sideways on a small screen.

Same problem, different words

Cutting the parcel list into at most D consecutive groups and minimizing the heaviest group is exactly Split Array Largest Sum. That page goes further into the partition DP and the proof that the greedy check is optimal; this one stays on the search template. Recognizing the match and saying so in an interview is a plus, as long as you still explain the steps.

Inputs that catch bugs

  • D equal to 1: the answer is the total.
  • D at least the number of parcels: the answer is the heaviest parcel.
  • All parcels the same weight, where ceil(total / D) is often the answer.
  • A heavy parcel at the very end, so the last day decides everything.
  • A single parcel.

Common errors

  • Starting lo at 1 with a check that does not reject oversized parcels: when D is large, it accepts a capacity smaller than the heaviest parcel and returns an answer that is too small.
  • Counting days from 0, so the final partial day is missed.
  • Mixing loop styles: while lo <= hi with hi = mid instead of hi = mid - 1, which never ends.
  • Sorting the weights first; the order is fixed by the problem.
  • Returning mid from inside the loop the first time a capacity works, which is a good capacity but not the smallest.

Talking it through

Fictional example

Spotting the monotonic check
Candidate
Given a capacity, I can count days in one pass: fill the ship until the next parcel won't fit, then start a new day.
Candidate
If capacity c works, c plus one works too, so the good capacities form a suffix. I'll binary search for the first good one.
Interviewer
What are your bounds?
Candidate
The ship has to hold the heaviest parcel, and it has to move the total in D trips, so the low end is the larger of those. The high end is the total weight. That's n times log of the total.

Where to go next

Continue with Find K Closest Elements, which binary searches a position with a less obvious condition, and The Skyline Problem for a heap-based sweep. Dungeon Game shows the same search on a starting value next to a DP that avoids it, and the Big-O cheat sheet explains why log W checks are so cheap.

Practising with Natively

Binary search bugs usually come from the loop details, so practise writing this one from scratch and explaining each line. On Mac or Windows, Natively can read the shipping problem from a screenshot in a practice session and show an approach and code in its overlay to compare with your bounds and loop condition. In a spoken mock, the transcript it keeps helps you check that you said why the search is allowed, not just that you used it. See Natively as an AI interview assistant.

Questions people ask

How do you solve Capacity to Ship Packages Within D Days?

Binary search the capacity. For a candidate capacity, simulate the days by loading parcels in order until the next one does not fit. The smallest capacity that needs at most D days is the answer.

What are the binary search bounds for Capacity to Ship Packages?

The low bound is the heaviest parcel, or the larger of that and the total divided by D rounded up. The high bound is the total weight, which ships everything in one day.

What is the time complexity of Capacity to Ship Packages Within D Days?

O(n log W), where n is the number of parcels and W the total weight: about log W checks, each a pass over the list.

Is Capacity to Ship Packages the same as Split Array Largest Sum?

Yes, in substance. Both cut an ordered list into at most a given number of consecutive groups and minimize the largest group sum.

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