DSA Factory
Free lessonsHeaps · Stage 0 · Smallest first · Step 2

Connect ropes

Repeatedly combine the two shortest ropes to minimize cumulative connection cost. About 8 minutes.

The rope connection cost

Suppose you have ropes of lengths 1, 2 and 4, and joining two ropes costs their combined length. If you connect 2 and 4 first (cost 6), then join 1 (cost 7), the total cost is 13. But if you connect 1 and 2 first (cost 3), then the 4 (cost 7), the total is only 10.

Long ropes that get joined early are paid for again and again, so join the short ones first.

Greedy strategy: always pick the two shortest ropes currently available.
Reinserting: the newly made rope must compete with the remaining ropes.
ropes = [4, 3, 2, 6] in a min-heap (smallest first)
2
0
3
1
4
2
6
3
smallestnext
cost
5

Pop the two shortest: 2 and 3. Joining them costs 5.

Move 1 of 4

Why a min-heap fits perfectly

Every turn, you must find and remove the two smallest numbers, and insert one new combined number. Sorting after every combine would be slow, and with many ropes that adds up quickly.

With a min-heap, each turn takes only about log n steps, so the whole job is fast: the heap keeps the shortest ropes at the top for you.

Pop twice: take out the two smallest.
Push the sum: add the cost to the total and put the new rope back.
In code
import heapq

if len(ropes) <= 1:
    return 0
heapq.heapify(ropes)
total = 0
while len(ropes) > 1:
    a = heapq.heappop(ropes)
    b = heapq.heappop(ropes)
    total += a + b
    heapq.heappush(ropes, a + b)
return total
Quick check

For ropes of lengths [1, 8, 3, 5], which two ropes should you connect first?

  1. A1 and 3
  2. B5 and 8
  3. C1 and 8
Show the answer

1 and 3. 1 and 3 are the two smallest lengths, incurring the minimum immediate cost of 4.

Your problem

Connect ropes

You are given an array ropes where ropes[i] is the length of the i-th rope. You can connect two ropes of lengths x and y into one rope at a cost of x + y. Return the minimum total cost to connect all ropes into one single rope. If there is only 0 or 1 rope, the cost is 0.

Example
ropes = [4, 3, 2, 6] → 29

0 ≤ ropes.length ≤ 100,000 · 1 ≤ ropes[i] ≤ 100,000 · the total can pass 2^31, so keep it in a 64-bit integer

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding