Minimum Cost to Connect Sticks - Problem

You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the i-th stick.

You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining.

Return the minimum cost of connecting all the given sticks into one stick in this way.

Input & Output

Example 1 — Basic Case
$ Input: sticks = [2,4,3]
Output: 14
💡 Note: Combine 2+3=5 (cost 5), then combine 5+4=9 (cost 9). Total cost = 5+9 = 14
Example 2 — Four Sticks
$ Input: sticks = [1,8,3,5]
Output: 30
💡 Note: Optimal: 1+3=4 (cost 4), 4+5=9 (cost 9), 8+9=17 (cost 17). Total cost = 4+9+17 = 30
Example 3 — Single Stick
$ Input: sticks = [20]
Output: 0
💡 Note: Only one stick, no combining needed, so cost is 0

Constraints

  • 1 ≤ sticks.length ≤ 104
  • 1 ≤ sticks[i] ≤ 104

Visualization

Tap to expand
Minimum Cost to Connect Sticks INPUT Array of Sticks 2 4 3 sticks = [2, 4, 3] 2 4 3 i=0 i=1 i=2 Build Min-Heap 2 3 4 ALGORITHM STEPS 1 Build Min-Heap Heap: [2, 3, 4] 2 Pop 2 + 3 = 5 Cost=5, Heap: [4, 5] 2 + 3 = 5 3 Pop 4 + 5 = 9 Cost=5+9=14, Heap: [9] 4 + 5 = 9 4 Done! One stick left Total Cost = 14 Cost Breakdown: 5 + 9 = 14 FINAL RESULT All sticks connected! 9 (Final Stick) Connection Tree 9 5 4 2 3 Output: 14 Key Insight: Always connect the two smallest sticks first! Using a Min-Heap ensures O(log n) extraction of minimum elements. Smaller sticks get reused more in subsequent joins, minimizing total cost. Time: O(n log n) | Space: O(n) TutorialsPoint - Minimum Cost to Connect Sticks | Greedy with Min-Heap Approach
Asked in
Amazon 42 Google 35 Facebook 28 Microsoft 22
38.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen