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

Problem: Each rescue boat carries at most two people and at most limit kg. Find the minimum number of boats (greedy: pair the heaviest with the lightest if possible).

Problem: Each rescue boat carries at most two people and at most `limit` kg. Find the minimum number of boats (greedy: pair the heaviest with the lightest if possible).
def boats(w, limit):
    w.sort(); i, j, trips = 0, len(w) - 1, 0
    while i <= j:
        if w[i] + w[j] <= limit: i += 1
        j -= 1; trips += 1
    return trips
print(boats([70, 50, 80, 50, 30, 20], 100), boats([40, 40, 40], 80))
What is printed?
  1. A. 2 2
  2. B. 3 3
  3. C. 3 2
  4. D. 4 2

Correct answer: C. 3 2

The heaviest person must go in some boat; if anyone can share with them, the lightest can, and pairing with the lightest leaves the most options for others (exchange argument). Sorted 20, 30, 50, 50, 70, 80: (20, 80), (30, 70), (50, 50) → 3. [40, 40, 40]: (40, 40) then 40 alone → 2. Pairing adjacent people after sorting (20+30, 50+50, 70, 80) wastes boats → 4. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic