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?- A. 2 2
- B. 3 3
- C. 3 2
- 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
- Problem: Count how many query words are subsequences of a long log string, using per-letter position lists and binary search (instead of…
- Problem: A candy-crush style cleaner repeatedly deletes any k equal adjacent letters (cascading) until none remain. A stack of (letter…
- Problem: Score a balanced bracket string: "()" = 1, AB = A + B, (A) = 2·A. Each innermost "()" at depth d contributes 2^d. python def…
- Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one…
- Problem: Evaluate an expression of non-negative integers with + − / (no brackets, / truncates toward zero) in one pass with a stack…
- Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the…