Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost.

Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost.
import heapq
def cost(r):
    heapq.heapify(r); total = 0
    while len(r) > 1:
        s = heapq.heappop(r) + heapq.heappop(r)
        total += s; heapq.heappush(r, s)
    return total
print(cost([4, 3, 2, 6]), cost([7]))
What is printed?
  1. A. 25 0
  2. B. 29 0
  3. C. 29 7
  4. D. 35 0

Correct answer: B. 29 0

Always join the two shortest (Huffman-style greedy): 2+3 = 5, 4+5 = 9, 6+9 = 15; total 5 + 9 + 15 = 29. Joining in the given order costs 7 + 13 + 19 = 39 – longer ropes get added repeatedly. A single rope costs nothing. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic