MediumNo. 1167LeetCode Premium
Minimum Cost to Connect Sticks — LeetCode 1167 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Greedy, Array, Heap (Priority Queue)
- Reading time
- 2 min
- Source
- leetcode.com
The 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 ith stick.
Example
- Input
- sticks = [2,4,3]
- Output
- 14
- Explanation
- You start with sticks = [2,4,3].
Python solution
class Solution:
def connectSticks(self, sticks: List[int]) -> int:
heapify(sticks)
ans = 0
while len(sticks) > 1:
z = heappop(sticks) + heappop(sticks)
ans += z
heappush(sticks, z)
return ansComplexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1167. Minimum Cost to Connect Sticks is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0502 | IPO | Hard |
| 0630 | Course Schedule III | Hard |
| 0857 | Minimum Cost to Hire K Workers | Hard |
| 1353 | Maximum Number of Events That Can Be Attended | Medium |
| 1383 | Maximum Performance of a Team | Hard |
| 1642 | Furthest Building You Can Reach | Medium |
Frequently asked questions
- How hard is LeetCode 1167. Minimum Cost to Connect Sticks?
LeetCode 1167. Minimum Cost to Connect Sticks is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1167. Minimum Cost to Connect Sticks?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 1167. Minimum Cost to Connect Sticks?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1167. Minimum Cost to Connect Sticks cover?
LeetCode 1167. Minimum Cost to Connect Sticks is tagged Greedy, Array and Heap (Priority Queue) on LeetCode.
- Is LeetCode 1167. Minimum Cost to Connect Sticks a premium problem?
Yes. LeetCode 1167. Minimum Cost to Connect Sticks is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.