Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Binary search

Smallest ship that clears the backlog in D days

Medium · Target 20 minutes · Binary search· Type asked at

Packages must be shipped in the order given. weights[i] is the weight of the i-th package. Each day the ship is loaded with a run of packages from the front, without exceeding its capacity. Return the smallest capacity that clears every package within days days.

Examples

InputOutputWhy
weights = [1,2,3,4,5,6,7,8,9,10], days = 515Days of 1–5, 6–7, 8, 9, 10.
weights = [3,2,2,4,1,4], days = 363+2, 2+4, 1+4.
weights = [1,2,3,1,1], days = 43A capacity of 2 needs five days.

Constraints

  • 1 ≤ days ≤ n ≤ 5 × 10⁴
  • 1 ≤ weights[i] ≤ 500
  • Packages keep their order

Hints

Hint 1

Ask the easier question first: given a capacity C, can you finish in the allowed number of days? That is one greedy pass.

Hint 2

If capacity C works, does C + 1 also work? That monotonicity is what makes binary search legal.

Hint 3

The answer is between max(weights) — a single package must fit — and sum(weights), which is one day.

Where people lose marks

  • Starting the search at 1 rather than max(weights): the feasibility check must still be written so it never loops forever on a package that cannot fit.
  • Returning the midpoint when the loop ends rather than the recorded low bound.
  • Using (lo + hi) / 2 with large bounds in C++ or Java. Prefer lo + (hi − lo) / 2.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.