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
- Put all lengths in a min-heap.
- Repeatedly pop the two smallest, add their sum to the cost and push the sum back.
- 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.