Minimum Cost to Connect Sticks
Always merge the two shortest sticks first
Every stick's length gets added to the running cost once for every merge it takes part in AFTER it is created. A stick combined early sits inside the pile through more later merges, so it must be a SHORT one — the two shortest sticks available should always be connected next. A min-heap keeps the two shortest on top with no scanning: pop twice, connect, push the sum back in, repeat.
Details
Animated on: Sticks = [2, 4, 3]. Repeatedly connect any two sticks for a cost equal to their summed length, until one stick remains. Return the minimum total cost.
Problem:Minimum Cost to Connect SticksMedium
Always merge the two shortest sticks first
step 1 / 8
Push the first stick, 4. One node, so it is trivially the root.
1FUNCTION minCostConnectSticks(sticks):2 heap <- BUILD MIN-HEAP FROM sticks3 cost <- 04 WHILE LENGTH(heap) > 15 a <- EXTRACT-MIN(heap)6 b <- EXTRACT-MIN(heap)7 cost <- cost + a + b8 INSERT (a + b) INTO heap9 RETURN cost
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- Push the first stick, 4. One node, so it is trivially the root.
- Push 2. It is smaller than the current root 4, so it sifts up and takes the root spot — heap = [2, 4].
- Push 3. 3 is bigger than root 2, so the min-heap property already holds — heap = [2, 4, 3].
- Round 1: extract the smallest stick, 2. The last element slides into the root and sifts down, so the heap stays valid — heap = [3, 4].
- Extract the next smallest, 3. Connecting 2 and 3 costs 5 — running total is 5. Push 5 back into the heap so it can be combined again later — heap = [4, 5].
- Round 2: extract the smallest stick, 4. The last element slides into the root and sifts down, so the heap stays valid — heap = [5].
- Extract the last other stick, 5. Connecting 4 and 5 costs 9 — running total is 14. Push 9 back in; only one stick remains, so the process stops.
- minCostConnectSticks([2, 4, 3]) = 14 — connect 2 and 3 first (cost 5), then merge that with 4 (cost 9); 5 + 9 = 14, matching the example.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.