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?- A. 5 3
- B. 6 2
- C. 7 3
- 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
- Problem: A courier eats through n ≤ 10⁵ piles of parcels, pile sizes up to 10⁹, at speed k per hour (a pile smaller than k still takes a…
- Problem: Place c routers at given positions on a road so the minimum distance between any two routers is as large as possible. python def…
- Problem: The function below should return the integer square root ⌊√x⌋. java static int isqrt(int x) { int lo = 0, hi = x, ans = 0; while…
- Problem: In an array where every element appears twice except one, and pairs sit next to each other, the array is sorted. Find the single…
- Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index. python def peak(a)…
- Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)). python def kth(a, b, k): if…