TRT
Sign in
mediumAdvancedLeetCode#Huffman merge#min-heap

Minimum cost to connect sticks

Join sticks into one, paying the sum of the two lengths each time, at minimum total cost, by always joining the two shortest.

The Runtime Theory Team1 min read
Taught inHuffman codingPro — members onlyHuffman coding gives frequent symbols short bit codes and rare ones long codes, with no code a prefix of another. Repeatedly merging the two rarest subtrees in a heap builds the provably shortest such code.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

insticks = [2, 4, 3]

out14

insticks = [1, 8, 3, 5]

out30

insticks = [5]

out0

Connecting two sticks of lengths x and y costs x + y and produces one stick of length x + y. Return the minimum cost to connect all sticks into one.

Before you code

Each stick's length is paid once for every join it takes part in, which is its depth in the tree of joins. Minimizing length × depth is exactly the Huffman problem.

Hints

  1. Put all lengths in a min-heap.
  2. Repeatedly pop the two smallest, add their sum to the cost and push the sum back.
  3. Stop when one stick remains. O(n log n).

Production & complexity notes

When solving Minimum cost to connect sticks on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Huffman coding to reinforce the underlying pattern.

What it practices

Huffman's greedy merge outside compression, from Huffman coding.

Not started

Sign in to save your learning progress.

Sign in to save