Tensorum
LeetCode 1011 · Binary Search on Answer

Capacity To Ship Packages Within D Days

LeetCode 1011 · Medium · solution, intuition & step-by-step walkthrough

Binary search capacity in [max(w), sum(w)] with a greedy day count.

MediumArrayBinary Search
225 msruntime · beats 48%
23.7 MBmemory · beats 94%
1approach
4accepted runs · last 3 Nov 2026

This is how I solved Capacity To Ship Packages Within D Days (LeetCode 1011), a medium problem from the Binary Search on Answer pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

A larger ship capacity never needs more days, so binary search the capacity. The smallest possible is the heaviest package; the largest is everything in one day. Check each guess by loading packages greedily in order.

Approach

  1. 1

    low = max(weights), high = sum(weights).

  2. 2

    Greedy: start a new day when the next package would overflow.

  3. 3

    days ≤ D → shrink high; else raise low.

How I solved it

Binary search + greedy checkPythonO(n log S) time
class Solution:
    def shipWithinDays(self, weights: list[int], days: int) -> int:
        def is_feasibile(max_capacity):
            req_days = 1
            cur_taken= 0
            for weight in weights:
                if cur_taken+weight>max_capacity:
                    req_days+=1
                    cur_taken=weight
                else:
                    cur_taken+=weight
            return True if req_days<=days else False
        low=max(weights)
        high =sum(weights)
        while low<=high:
            mid = (low+high)//2
            if is_feasibile(mid):
                high = mid-1
            else:
                low = mid+1
        return low
Loading the step-through…

Capacity To Ship Packages Within D Days — FAQ

What is the intuition behind Capacity To Ship Packages Within D Days?

A larger ship capacity never needs more days, so binary search the capacity. The smallest possible is the heaviest package; the largest is everything in one day. Check each guess by loading packages greedily in order.

How do you solve Capacity To Ship Packages Within D Days (LeetCode 1011)?

1. low = max(weights), high = sum(weights). 2. Greedy: start a new day when the next package would overflow. 3. days ≤ D → shrink high; else raise low.

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

Time: O(n log S). Space: O(1). (Accepted approach: Binary search + greedy check.)

What are common mistakes in Capacity To Ship Packages Within D Days?

Packages must stay in order — no sorting.