15% off all plans & roadmaps Use code

See plans

Capacity To Ship Packages Within D Days

Updated

TL;DR: You need the smallest ship capacity that moves every package, in order, within the day limit. Binary search the capacity, and check each candidate with a greedy scan that fills each day as far as it can.

Problem

A conveyor belt carries packages from one port to another. The ith package on the belt weighs weights[i], and all the packages must ship within days days.

Each day, we load the ship with packages from the belt, in the order given by weights. We may not load more weight than the ship's maximum capacity. Return the least capacity that ships all the packages within days days.

Example 1

Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
Explanation:
A capacity of 15 is the minimum to ship all the packages in 5 days, like this: 1st day: 1, 2, 3, 4, 5. 2nd day: 6, 7. 3rd day: 8. 4th day: 9. 5th day: 10.

The cargo must ship in the order given. A capacity of 14 is not allowed with a split such as (2, 3, 4, 5), (1, 6, 7), (8), (9), (10).

Example 2

Input: weights = [3,2,2,4,1,4], days = 3
Output: 6
Explanation: A capacity of 6 is the minimum to ship all the packages in 3 days, like this: 1st day: 3, 2. 2nd day: 2, 4. 3rd day: 1, 4.

Example 3

Input: weights = [1,2,3,1,1], days = 4
Output: 3
Explanation: 1st day: 1. 2nd day: 2. 3rd day: 3. 4th day: 1, 1.

Constraints

  • 1 <= days <= weights.length <= 5 * 10^4
  • 1 <= weights[i] <= 500

Constraints that matter

  • The weights are at most 500 and the array holds up to 5 * 10^4 packages, so the sum can reach 2.5 * 10^7. Trying every capacity in that range with a full scan each time is too slow.
  • The capacity can never be below the heaviest package. That gives a natural lower bound of max(weights).
  • days can be as small as 1, so the answer can be as large as the total weight. That gives the upper bound sum(weights).
  • The order is fixed. You cannot sort or regroup the packages, so the check has to scan them in sequence.

View on LeetCode

Hints

Hint 1

The question asks for a capacity, which is a number inside a known range.

Hint 2

Try every capacity from the heaviest package up to the total weight, in increasing order.

Solution

Intuition

The question asks for a capacity, which is a number inside a known range. The smallest possible capacity is max(weights), and the largest useful one is sum(weights). When you search for a value across a known range, the pattern is binary search on the answer.

Picture a row of numbered gates, where every gate from some point onward opens and every gate before it stays shut. The gate numbers are the candidate capacities, and the inspector who tests one gate is the greedy day count.

The second part is a yes or no question: can this capacity ship everything within days days? A larger capacity never needs more days than a smaller one. So the answers across the range look like no, no, no, yes, yes, yes. You only need to find the first yes.

The yes or no check must be fast. For a fixed capacity, a greedy scan works. Load each day with packages in order until the next one would overflow, then start a new day. Each day takes the longest prefix that fits, so no other split uses fewer days for that capacity.

Watch the pattern animation

Worked example

Input: weights = [3, 2, 2, 4, 1, 4], days = 3
Output: 6
Explanation: The heaviest package weighs 4, so the capacity must be at least 4. A capacity of 6 packs the packages into three days: [3, 2], [2, 4], [1, 4]. A capacity of 5 needs four days, so 6 is the smallest value that works.

Approach 1: Brute force

Try every capacity from the heaviest package up to the total weight, in increasing order. For each capacity, run the greedy day count. Return the first capacity that finishes within days days.

This is correct. The first feasible capacity is the smallest one, so returning it gives the minimum. The cost comes from how many capacities you try, and each try rescans the whole array.

Steps

  1. Compute maxW as the largest weight and total as the sum of all weights.
  2. For each capacity from maxW to total, in increasing order, run the day count.
  3. Start daysNeeded at 1 and load at 0.
  4. For each weight, if load + w is more than the capacity, add a day and set load to 0. Then add w to load.
  5. If daysNeeded is at most days, return the capacity.
  6. If no capacity works, return total. Valid input never reaches this line.

Dry run

Start at capacity 4, the heaviest package. Day 1 takes 3, because 3 + 2 = 5 is more than 4. Day 2 takes 2, 2, because 2 + 2 = 4 fits. Day 3 takes 4, day 4 takes 1 and day 5 takes 4.

That is five days, which is more than 3, so 4 fails.

Try capacity 5. Day 1 takes 3, 2. Day 2 takes 2 alone, since 2 + 4 is more than 5. Day 3 takes 4, 1, and day 4 takes 4 alone. That is four days, so 5 fails.

Try capacity 6. Day 1 takes 3, 2. Day 2 takes 2, 4. Day 3 takes 1, 4. That is three days, which is at most 3, so the function returns 6.

Complexity

TimeO(N * S)
SpaceO(1)

Let N be the number of packages and S the sum of the weights. The outer loop tries at most S capacities, since the range runs from max(weights) to S. Each check reads the array once with constant work per package, so one check costs O(N).

Multiplying the two counts gives O(N * S) time. The worst case is days = 1, where the loop runs all the way to S. The extra space is O(1).

PythonTested in our runner

class Solution:
    def shipWithinDays(self, weights: List[int], days: int) -> int:
        # Try each capacity in increasing order and return the first that works
        max_w = max(weights)
        total = sum(weights)
        for capacity in range(max_w, total + 1):
            days_needed = 1
            load = 0
            for w in weights:
                if load + w > capacity:
                    days_needed += 1
                    load = 0
                load += w
            if days_needed <= days:
                return capacity
        return total

The On Answer / Condition Function infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

On Answer / Condition Function

Part of Binary Search Patterns

Approach 2: Binary search on the answerOptimalOn Answer / Condition Function

What's slow: brute force asks the yes or no question at every capacity from the heaviest package upward. Most of those checks repeat what a neighbouring check already showed.

The insight that fixes it: the answers switch from no to yes exactly once, and they never switch back. A binary search finds that switch. Each check cuts the candidate range in half, so you need about log S checks instead of up to S.

Keep right at a value known to work, and move left up past values known to fail. When the two meet, that value is the smallest capacity that works.

Steps

  1. Set left to max(weights) and right to sum(weights).
  2. While left is less than right, compute mid = left + (right - left) // 2.
  3. Run the greedy day count for capacity mid. Start at 1 day and a load of 0.
  4. If the day count is at most days, set right = mid.
  5. Otherwise set left = mid + 1.
  6. When the loop ends, return left.

Dry run

Start with left = 4 and right = 16, the sum of the weights. Each row shows one iteration of the loop.

Stepleftrightmiddays needed at midfeasible?update
1416102yesright = 10
241073yesright = 7
34754noleft = 6
46763yesright = 6
566stopnonenonereturn 6

Row 1 groups [3, 2, 2] and [4, 1, 4]. Row 2 groups [3, 2, 2], [4, 1], [4].

Row 3 is the key case. Capacity 5 needs four days, so every capacity up to 5 fails, and the answer must be above 5. Row 4 confirms that 6 works. The loop ends with left = right = 6, which matches the expected output.

Complexity

TimeO(N log S)
SpaceO(1)

Let N be the number of packages and S the sum of the weights. The range from left to right starts at most S wide and halves on each iteration, so there are about log2(S) + 1 iterations. For S = 2.5 * 10^7 that is about 25 checks.

Each check reads the array once with constant work per package, so it costs O(N). The total time is O(N log S). The loop stores only left, right, mid, the load and a day counter, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def shipWithinDays(self, weights: List[int], days: int) -> int:
        def can_ship(capacity: int) -> bool:
            # Greedy: fill each day as far as possible in order
            days_needed = 1
            load = 0
            for w in weights:
                if load + w > capacity:
                    days_needed += 1
                    load = 0
                load += w
            return days_needed <= days

        # The answer lies between the heaviest package and the total weight
        left = max(weights)
        right = sum(weights)
        while left < right:
            mid = left + (right - left) // 2
            if can_ship(mid):
                right = mid      # mid works, so the answer is mid or smaller
            else:
                left = mid + 1   # mid fails, so the answer is larger
        return left

Common mistakes

  • Starting left at 0 or 1. A capacity below the heaviest package can never load that package, so the check sees values it should never test. Start left at max(weights).
  • Writing right = mid - 1 after a feasible check. That drops mid, which can be the smallest valid capacity. Keep it with right = mid.
  • Writing left = mid after an infeasible check. When left and right are one apart, mid equals left and the loop never ends. Use left = mid + 1.
  • Resetting load = 0 for a new day and forgetting to add the package that did not fit. That package starts the new day, so add its weight to the new load.
  • Starting daysNeeded at 0. The first day is always used, so the count starts at 1. Starting at 0 undercounts the days and accepts capacities that are too small.
  • Testing daysNeeded < days. The problem allows exactly days days, so the check is daysNeeded <= days.

Edge cases

  • days equals the number of packages. Each package gets its own day, so the answer is max(weights).
  • days equals 1. Everything ships in one load, so the answer is sum(weights).
  • A single package, weights = [7] with days = 1. The answer is 7.
  • All weights equal, weights = [5, 5, 5, 5] with days = 2. Two packages fit per day, so the answer is 10.
  • Many packages at the maximum weight, 50000 copies of 500 with days = 50000. Each package gets its own day, so the answer is 500.
  • The largest sum, 50000 packages of weight 500 with days = 1. The answer is 2.5 * 10^7, which fits in a 32-bit int.

Follow-ups interviewers ask

What if the packages could ship in any order?
The problem becomes bin packing with a fixed number of bins, which is NP-hard. The greedy check depends on the fixed order, so it no longer gives the minimum. You would need a different method, and this binary search would not guarantee the answer.
Can you solve it in O(1) extra space?
The optimal approach already uses O(1) extra space. It keeps left, right, mid, a running load and a day counter. The input array is read in place.
What if you must print the day-by-day split?
Run the greedy check once more at the answer capacity. Start a new group every time the next package would overflow the load. Building the groups takes O(N) output space, and the working memory stays O(1).

Capacity To Ship Packages Within D Days FAQ

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

The binary search version runs in O(N log S) time, where N is the number of packages and S is the sum of the weights. The brute force version runs in O(N * S) time. The binary search version is the one to write in an interview.

Why use binary search for Capacity To Ship Packages Within D Days?

The answer is a capacity, and a check tells you whether a capacity works. If one capacity works, every larger one works too. So the answers switch from no to yes once, and binary search finds that switch in about log S checks.

Can Capacity To Ship Packages Within D Days be solved in O(1) extra space?

Yes. The binary search keeps a few integers, and the greedy check keeps a day counter and a running load. Nothing grows with the input size.

Why not sort the weights first?

Sorting breaks the required shipping order. The day split depends on the sequence, so a sorted array can need a different number of days. The problem does not allow reordering.

Why is a monotonic stack not the right tool here?

A monotonic stack answers next-greater or next-smaller questions for each element. This problem asks for one capacity that splits the whole sequence into groups. No stack tracks that threshold.

Does the greedy day split use the fewest days?

Yes, for any fixed capacity. Each day loads the longest prefix that fits, so no later cut can use fewer days. That is why the check can trust its day count.

Asked at

See which companies ask this — Pro

Practise it