#1046
Last Stone Weight
EasyArrayHeap (Priority Queue)Heap (Priority Queue)Greedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Using a max-heap (priority queue) allows us to efficiently retrieve and remove the two heaviest stones in logarithmic time, making the process much faster than sorting the entire array each time.
⚙️
Algorithm
4 steps- 1Step 1: Create a max-heap from the stones array.
- 2Step 2: While there are at least two stones, extract the two heaviest stones.
- 3Step 3: Smash them together and, if there's a remaining weight, add it back to the heap.
- 4Step 4: Return the last remaining stone or 0 if no stones are left.
solution.py12 lines
1# Full working Python code
2import heapq
3
4def lastStoneWeight(stones):
5 stones = [-s for s in stones] # Convert to max-heap
6 heapq.heapify(stones)
7 while len(stones) > 1:
8 x = -heapq.heappop(stones)
9 y = -heapq.heappop(stones)
10 if x != y:
11 heapq.heappush(stones, -(x - y))
12 return -stones[0] if stones else 0ℹ
Complexity note: The time complexity is O(n log n) due to the heap operations (insert and extract) being logarithmic, and we perform these operations for each stone.
- 1Using a max-heap allows for efficient retrieval of the two heaviest stones.
- 2Simulating the game step-by-step helps in understanding the problem better.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.