Minimum Cost to Connect Sticks: The Greedy Heap Proof in Two Minutes

The problem

You have sticks with positive lengths. Joining two sticks of lengths a and b costs a + b and produces one stick of length a + b. Return the minimum total cost to join all sticks into one. For [2, 4, 3] the answer is 14: join 2 and 3 for 5, then 5 and 4 for 9.

The greedy

Always join the two shortest sticks. A min-heap gives you both in O(log n), and you repeat n - 1 times, so the total is O(n log n).

import heapq

def connect_sticks(sticks):
    heapq.heapify(sticks)
    cost = 0
    while len(sticks) > 1:
        a = heapq.heappop(sticks)
        b = heapq.heappop(sticks)
        cost += a + b
        heapq.heappush(sticks, a + b)
    return cost

Why it is optimal

Picture the joins as a binary tree with the original sticks as leaves. Each stick's length is paid once for every join above it, so the total cost is the sum of length times depth.

To minimize that sum, the shortest sticks should sit deepest. Swapping a short deep leaf with a longer shallow one can only lower the cost, so some optimal tree has the two shortest sticks as siblings at the bottom. Join them, treat the result as a new stick, and the same argument applies again. This is exactly the Huffman coding proof, and naming it is worth saying in the interview.

Common mistakes

Sorting once and joining left to right: after the first join the new stick may not be the smallest, so you need the heap.

Forgetting the single-stick case, which costs 0.

Disclosure

I work on https://www.linkjob.ai/, an AI interview copilot that helps with coding and greedy-proof questions in real time.

Minimum Cost to Connect Sticks: The Greedy Heap Proof in Two Minutes

By linkjob-ai

Minimum Cost to Connect Sticks: The Greedy Heap Proof in Two Minutes

  • 6