DSA Heaps

Minimum Cost to Connect Sticks

Huffman-style merge — always combine the two shortest sticks via a min-heap.

Medium
Time O(n log n) Space O(n)
LeetCode
4 min read
heaps greedy

Problem#

Each merge combines two sticks of lengths x and y into one of length x + y at cost x + y. Return the minimum total cost to merge all sticks into one.

Examples#

  • [2,4,3]14 (merge 2+3=5 cost 5, then 5+4=9 cost 9, total 14)
  • [1,8,3,5]30

Constraints#

  • 1 <= sticks.length <= 10^4.

Approach#

Min-heap. Repeatedly pop the two smallest, push their sum, accumulate the cost. Pure Huffman coding.

Solution#

Minimum Cost to Connect Sticks
class Solution {
public:
int connectSticks(vector<int>& sticks) {
priority_queue<int, vector<int>, greater<int>> pq(sticks.begin(), sticks.end());
int total = 0;
while (pq.size() > 1) {
int a = pq.top(); pq.pop();
int b = pq.top(); pq.pop();
total += a + b;
pq.push(a + b);
}
return total;
}
};

Editorial#

Greedy works because the cost of merging two sticks contributes to every subsequent merge they participate in. By always combining the two smallest, we minimize the depth of each leaf in the merge tree — exactly Huffman’s argument for optimal-prefix codes.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.