InterviewHubPRO
Section Overview
Q72

Question 72 of 100

Part 8: Heaps, Priority Queues & Tries (65 - 72)

72%
DSA Patterns (Multi-Lang)•Part 8: Heaps, Priority Queues & Tries (65 - 72)

Minimum Cost to Connect Sticks.

In Simple Words: Huffman Coding greedy pattern: Min-Heap of stick lengths. Repeatedly extract the two shortest sticks, sum them, add to total cost, and push sum back into heap.

  • Time: $O(N \log N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
import heapq

def connectSticks(sticks: list[int]) -> int:
    heapq.heapify(sticks)
    total_cost = 0
    while len(sticks) > 1:
        cost = heapq.heappop(sticks) + heapq.heappop(sticks)
        total_cost += cost
        heapq.heappush(sticks, cost)
    return total_cost