Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining packages without exceeding capacity C. Find the least C.

Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining packages without exceeding capacity C. Find the least C.
def days_needed(w, cap):
    days, load = 1, 0
    for x in w:
        if load + x > cap:
            days += 1; load = 0
        load += x
    return days
def least_cap(w, D):
    lo, hi = max(w), sum(w)
    while lo < hi:
        mid = (lo + hi) // 2
        if days_needed(w, mid) <= D: hi = mid
        else: lo = mid + 1
    return lo
print(least_cap([3, 2, 2, 4, 1, 4], 3), least_cap([1, 2, 3, 1, 1], 4))
What is printed?
  1. A. 5 3
  2. B. 6 2
  3. C. 7 3
  4. D. 6 3

Correct answer: D. 6 3

Binary search on the answer: more capacity never needs more days, so feasibility is monotonic. Search between max(w) (every package must fit) and sum(w) (one day). Capacity 6 ships [3,2], [2,4], [1,4]; 5 needs 4 days. For the second list, 3 gives [1,2], [3], [1,1]. Cost O(n log(sum)). Starting lo at 1 instead of max(w) would let days_needed accept impossible capacities.

More Coding Interview Problems questions

Exams that ask this topic