Capacity To Ship Packages Within D Days

Medium Binary Search

Problem

Given an array weights representing the weights of packages and an integer days, return the least weight capacity of a ship that will result in all the packages being shipped within days days.

  • 1 ≤ days ≤ weights.length ≤ 5 * 10⁴
  • 1 ≤ weights[i] ≤ 500

Example

Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15

A brute-force approach would try every capacity from the heaviest package (10) up to the sum of all weights (55), checking if the packages can be shipped within 5 days. For capacity 15, the ship can load packages as follows: Day 1: [1,2,3,4,5], total 15; Day 2: [6,7], total 13; Day 3: [8], total 8; Day 4: [9], total 9; Day 5: [10], total 10. This is the minimal capacity that allows shipping within 5 days.

Approach

Straightforward Solution

A brute-force approach tries every capacity from max(weights) to sum(weights), simulating the shipping process for each capacity. This approach is O(n * sum(weights)) and is too slow for large inputs.

Core Observation

The minimal ship capacity must be at least the heaviest package and at most the sum of all package weights. The problem reduces to finding the smallest capacity in this range that allows shipping within the given days.

Path to Optimal

Recognizing that the feasibility of shipping within days is a monotonic predicate with respect to capacity allows the use of binary search. If a capacity can ship within days, any larger capacity can also ship within days. If it cannot, any smaller capacity also cannot. This monotonicity enables efficient search for the minimal feasible capacity.

Optimal Approach

Use binary search between max(weights) and sum(weights). For each mid capacity, simulate shipping by accumulating package weights until exceeding capacity, then increment day count. If the total days used is within the allowed days, move the right boundary to mid; otherwise, move the left boundary to mid + 1. Return the left boundary after convergence.

Time

O(n log S)

Where n is the number of packages and S is the sum of weights. Each binary search iteration takes O(n) to simulate shipping, and the search space is at most sum(weights), leading to O(log S) iterations.

Space

O(1)

Only a few variables are used for counters and boundaries; no additional data structures proportional to input size are needed.

Pattern Spotlight

Binary Search on Answer Space (Feasibility Check)

When the problem asks for a minimal or maximal value satisfying a monotonic feasibility condition, use binary search on the answer space by defining a predicate that checks feasibility and narrowing the search range accordingly.

Solution

1class Solution:
2 def shipWithinDays(self, weights: List[int], days: int) -> int:
3 def canShip(capacity):
4 used_days = 1
5 curr_weight = 0
6
7 for weight in weights:
8 if curr_weight + weight > capacity:
9 used_days += 1
10 curr_weight = 0
11
12 curr_weight += weight
13
14 return used_days <= days
15
16 l, r = max(weights), sum(weights)
17
18 while l < r:
19 capacity = (l + r) // 2
20
21 if canShip(capacity):
22 r = capacity
23 else:
24 l = capacity + 1
25
26 return l

Step-by-Step Solution

1

Simulate Shipping to Check Feasibility of Capacity

3def canShip(capacity):
4 used_days = 1
5 curr_weight = 0
7 for weight in weights:
8 if curr_weight + weight > capacity:
9 used_days += 1
10 curr_weight = 0
12 curr_weight += weight
14 return used_days <= days

Objective

To determine if all packages can be shipped within the given days using a specified ship capacity.

Key Insight

By iterating through the package weights and accumulating them until the capacity is exceeded, the algorithm counts how many days are needed to ship all packages. This simulation directly tests the feasibility predicate required for binary search. It leverages the problem's sequential loading constraint and ensures that the capacity is respected daily.

Interview Quick-Check

Core Logic

The simulation accumulates package weights until exceeding capacity, then increments the day count and resets the current load, effectively partitioning packages into days.

State & Boundaries

Initialize used_days to 1 and curr_weight to 0 to represent the first day and current load.

Common Pitfalls & Bugs

Forgetting to reset curr_weight after incrementing used_days leads to incorrect day counts.

2

Apply Binary Search to Find Minimal Feasible Capacity

16l, r = max(weights), sum(weights)
18while l < r:
19 capacity = (l + r) // 2
21 if canShip(capacity):
22 r = capacity
23 else:
24 l = capacity + 1
26return l

Objective

To efficiently narrow down the minimal ship capacity that allows shipping within the given days using binary search.

Key Insight

The search space is bounded by the heaviest package and the sum of all weights. By repeatedly checking the feasibility of the midpoint capacity and adjusting the search boundaries accordingly, the algorithm converges to the minimal capacity. This approach exploits the monotonicity of the feasibility predicate and avoids exhaustive search.

Interview Quick-Check

Core Logic

Binary search adjusts the search boundaries based on the feasibility check: if capacity is sufficient, search left half; otherwise, search right half.

State & Boundaries

The loop continues while left < right, ensuring convergence to the minimal feasible capacity.

Common Pitfalls & Bugs

Incorrectly updating boundaries (e.g., not adding 1 when capacity is insufficient) can cause infinite loops or incorrect results.

Line Analysis

This solution has 5 Critical lines interviewers watch for.

Line 14 Critical
return used_days <= days

Return whether the total days used is within the allowed days.

This boolean result serves as the feasibility predicate for binary search, determining if the capacity is sufficient.

Line 26 Critical
return l

Return the minimal capacity found after binary search completes.

At loop termination, left equals the minimal feasible capacity, which is the problem's solution.

Line 8 Critical
if curr_weight + weight > capacity:

Check if adding the current package exceeds the capacity.

This condition detects when the current day's load would surpass the ship's capacity, triggering a day increment.

Line 9 Critical
used_days += 1

Increment the day count when capacity is exceeded.

Increasing the day count reflects starting a new shipping day due to capacity overflow, critical for feasibility calculation.

Line 21 Critical
if canShip(capacity):

Check if shipping is feasible with the current midpoint capacity.

This check guides the binary search direction by testing the feasibility predicate.

Line 10 Core
curr_weight = 0

Reset the current weight to zero for the new day.

Resetting current weight ensures the new day's load starts fresh, preventing carryover from previous day.

Line 16 Core
l, r = max(weights), sum(weights)

Initialize the binary search boundaries: left as max package weight, right as sum of all weights.

Setting boundaries to these values ensures the search space includes all feasible capacities, with left as the minimal possible capacity and right as the maximal.

Line 22 Core
r = capacity

If feasible, move the right boundary to the midpoint to search for smaller capacity.

Reducing the right boundary narrows the search to smaller capacities that might still be feasible, aiming for minimal capacity.

Line 23 Core
else:

If not feasible, move the left boundary to midpoint plus one to search larger capacities.

Increasing the left boundary excludes insufficient capacities, ensuring eventual convergence to a feasible solution.

Line 4 Core
used_days = 1

Initialize the count of days used to 1.

Starting with one day assumes shipping begins immediately, and days increment only when capacity is exceeded.

Line 5 Core
curr_weight = 0

Initialize the current weight loaded on the ship to 0.

This variable tracks the cumulative weight loaded on the current day, essential for capacity checks.

Line 12 Core
curr_weight += weight

Add the current package weight to the current day's load.

Accumulate package weights to simulate loading until capacity is reached or exceeded.

Line 18 Core
while l < r:

Continue binary search while left boundary is less than right.

This loop condition ensures the search space shrinks until the minimal feasible capacity is found.

Line 19 Core
capacity = (l + r) // 2

Calculate the midpoint capacity between left and right.

Midpoint selection divides the search space, enabling logarithmic convergence.

Line 3 Standard
def canShip(capacity):

Define a helper function to check if shipping is possible with a given capacity.

Encapsulating the feasibility check as a helper function isolates the logic needed for binary search, improving code clarity and reusability.

Line 7 Standard
for weight in weights:

Iterate over each package weight in order.

Sequential iteration respects the problem constraint that packages must be shipped in order without reordering.

Line 24 Standard
l = capacity + 1

Continue the binary search loop with updated boundaries.

This iteration progressively narrows the search space until left equals right.

Test Your Understanding

Why is binary search applicable on the capacity range, and how does the feasibility check ensure correctness?

Because the feasibility of shipping all packages within the given days is monotonic with respect to capacity: if a capacity can ship within days, all larger capacities can too; if it cannot, all smaller capacities cannot. This monotonicity allows binary search to efficiently find the minimal capacity that satisfies the condition.

Related Problems

Binary Search pattern

Don't just read it. Drill it.

Reconstruct Capacity To Ship Packages Within D Days from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Capacity To Ship Packages Within D Days drill

or drill a free problem