Data Structures & AlgorithmsHardProduct Company SDE · greedy heap round

Problem: Merging ropes of lengths 2, 3, 4 costs the sum of the two lengths merged each time, always merging the two shortest. What is the total cost? Run the heap code.

Problem: Merging ropes of lengths 2, 3, 4 costs the sum of the two lengths merged each time, always merging the two shortest. What is the total cost? Run the heap code.
import heapq
h = [4, 3, 2]
heapq.heapify(h)
c = 0
while len(h) > 1:
    x = heapq.heappop(h)
    y = heapq.heappop(h)
    c += x + y
    heapq.heappush(h, x + y)
print(c)
What is printed?
  1. A. 16
  2. B. 9
  3. C. 14
  4. D. 5

Correct answer: C. 14

Merging 2 and 3 costs 5, then 4 and 5 cost 9, for 14. Merging the two largest first (3 + 4, then 7 + 2) costs 16, reporting only the final rope length gives 9, and a loop bound of len(h) > 2 stops after the first merge (5).

More Coding Interview Problems questions

Exams that ask this topic