Ship Packages Within D Days
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Interview workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Interview workspace
Problem
Implement Solution.shipWithinDays(weights, days). Packages must ship in input order, each day taking a contiguous prefix of remaining packages without exceeding capacity. Return the minimum capacity completing all packages within days.
Starter code
class Solution:
def shipWithinDays(self, weights, days):
passTest cases
five-days
{
"args": [
[
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
],
5
]
}Expected: 15
Wizard outline
- Step 1: Initialize Solution.shipWithinDays
Replace the empty starter with the first real state owned by Solution.shipWithinDays. A small, named state is easier to verify than a complete algorithm. Establish it before adding the branch or loop that changes it.
- Step 2: Pass the Three Days case
Complete the readable core algorithm for one representative Interview case. Binary-search capacity using a greedy ordered packing simulation as a monotone predicate.
- Step 3: Harden the Five Days boundary
Repair the reviewed boundary and pass the complete submission contract. Greedy packing uses the fewest possible days for a fixed capacity because delaying a package cannot reduce later load. Feasible capacities form a suffix, so lower-bound search returns the minimum feasible one.
Footguns and prerequisites
- The lower bound is max(weights), because a package cannot be split across days.
- arrays strings two pointers sliding window
Reviewed references
Practice prerequisites
- Minimize a Feasible Value(opens in a new tab)
Minimize a Feasible Value isolates left is the first unresolved candidate and right is always a feasible candidate, so the smallest feasible value remains inside [left, right]. That focused state discipline is required when implementing ship packages within days as a complete Interview Problem.
Recommended approach and implementation
Binary-search capacity between the heaviest package and total weight. Greedily start a new day whenever the next package would exceed a proposed capacity.
Why it works: Greedy packing uses the fewest possible days for a fixed capacity because delaying a package cannot reduce later load. Feasible capacities form a suffix, so lower-bound search returns the minimum feasible one.
class Solution:
def shipWithinDays(self, weights, days):
"""
Checkpoint 1: initialize the state owned by this Interview contract.
Checkpoint 2: assemble the primary transition without hiding the boundary.
"""
left, right = max(weights), sum(weights)
while left < right:
capacity = (left + right) // 2
used_days = 1
load = 0
for weight in weights:
if load + weight > capacity:
used_days += 1
load = 0
load += weight
if used_days <= days:
right = capacity
else:
left = capacity + 1
return left