Minimum Cost to Connect Sticks
You have some sticks with positive integer lengths, given as the array sticks. You can join any two sticks of lengths x and y into one stick of length x + y, which costs x + y. Keep joining until one stick is left.
Return the lowest total cost to join all the sticks into one.
Example 1
Input: sticks = [2, 4, 3] Output: 14
Join 2 and 3 for a cost of 5, leaving [5, 4]. Then join 5 and 4 for a cost of 9. The total is 14.
Example 2
Input: sticks = [1, 8, 3, 5] Output: 30
Constraints
1 <= sticks.length <= 100001 <= sticks[i] <= 10000
Approach
Trying every order of joins grows exponentially. Look at what each join costs instead: every original stick's length is added to the total once for each join it takes part in. Long sticks should take part in as few joins as possible, which means joining the shortest sticks first and the longest ones last.
That makes a greedy rule safe: always join the two shortest sticks available. A min-heap supports this directly. Pop the two smallest lengths, add their sum to the cost and push the joined stick back, until one stick is left. This is the same idea behind Huffman coding.
Steps
- Put all the stick lengths in a min-heap and set
costto0. - While the heap holds more than one stick, pop the two smallest.
- Add their sum to
costand push the sum back onto the heap. - Return
cost.
import heapq
from typing import List
def connect_sticks(sticks: List[int]) -> int:
heap = list(sticks)
heapq.heapify(heap)
cost = 0
while len(heap) > 1:
first = heapq.heappop(heap) # always join the two shortest sticks
second = heapq.heappop(heap)
cost += first + second
heapq.heappush(heap, first + second)
return costComplexity
- Time:
O(n log n). There aren - 1joins, each with a few heap operations. - Space:
O(n)for the heap.
Common mistakes
- Sorting once and joining from left to right. A joined stick can be longer than the next stick in the sorted list, so you need a heap to keep finding the two shortest.
- Returning the final stick's length instead of the total cost of all joins.
- Returning something other than 0 for a single stick, which needs no joins.