KatInterview

Smallest Conveyor Load Limit for Sequential Parcels

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchgreedysearch-on-answer

Last updated

Find the minimum per-day load limit that moves an ordered list of parcels in at most a given number of days, using binary search on the answer with a greedy feasibility check.

A warehouse has a queue of parcels that must be sent out by truck, one trip per day. Each parcel has a weight, and the parcels have to be sent in the order they appear in the queue.

You are given the parcel weights in queue order and the number of days available. Return the smallest daily load limit that allows every parcel to be sent within that many days.

Rules

  • On each day the truck takes a contiguous block of parcels, beginning with the first parcel that has not been sent yet. Parcels cannot be split, skipped, or rearranged.
  • The combined weight of the parcels taken on a single day must not exceed the load limit.
  • Every parcel must be sent within days days. Using fewer days is allowed.
  • The load limit is a positive integer. Return the smallest limit for which this is possible.

Function

Implement smallest_load_limit(weights, days):

  • weights: list of integers, where weights[i] is the weight of the i-th parcel in queue order.
  • days: integer, the maximum number of days allowed.
  • Returns: an integer, the minimum feasible daily load limit.

Constraints

  • 1 <= len(weights) <= 10^5
  • 1 <= weights[i] <= 10^4
  • 1 <= days <= len(weights)
  • The total weight is at most 10^9, so the answer fits in a signed 32-bit integer.

Examples

Example 1

Input: smallest_load_limit([4, 8, 2, 5, 7, 3, 6], 3)

Output: 14

Example 2

Input: smallest_load_limit([9, 1, 1, 1], 2)

Output: 9

Example 3

Input: smallest_load_limit([5, 2, 6], 1)

Output: 13

Hints

Hint 1

Flip the question: instead of finding the limit directly, ask how many days a given limit would need.

Hint 2

For a fixed limit, loading parcels greedily (start a new day only when the next parcel would overflow) gives the fewest days. Larger limits never need more days, so the feasible limits form a suffix of the possible values.

Hint 3

Binary search between max(weights) (the heaviest parcel must fit) and sum(weights) (everything in one trip), using the first-true pattern: hi = mid on success, lo = mid + 1 on failure.