Last Stone Weight (LeetCode 1046): Solution and Explanation
You have a pile of stones with positive weights. Repeatedly take the two heaviest and smash them: equal stones both disappear, and otherwise the heavier one survives with its weight reduced by the lighter one. Return the weight of the final stone, or 0 if nothing is left.
Watch it run step by step
Try your own input and write the code →Intuition
The rules are a direct simulation, so the only real question is how to keep finding the two heaviest stones quickly. The naive way is to sort the list every round, or scan it twice for the two largest values. Either costs at least O(n) per round, and with up to n rounds the total becomes O(n²) or worse.
What you actually need is a structure that hands you the largest element, lets you remove it, and lets you add a new element, all cheaply. That is exactly a max heap, where each of those operations is O(log n). Each round pops two stones and pushes at most one back, so the heap shrinks by at least one stone per round and the simulation ends after at most n - 1 rounds.
Python's heapq module only provides a min heap. The standard workaround is to store every weight as its negative. The most negative number is the smallest in heap order but corresponds to the heaviest stone, so popping the minimum gives you the maximum weight once you flip the sign back. The same trick applies when you push the remainder: push -(first - second).
When the loop ends, the heap holds either one stone or none. If one is left, return its weight with the sign flipped back; if the heap is empty, every stone was destroyed and the answer is 0.
Approach: Max heap simulation
- Build
heapfrom the negated weights and callheapq.heapifyto arrange it in O(n). - While the heap holds more than one stone, pop twice and negate to get the heaviest
firstand the second heaviestsecond. - If
first != second, push-(first - second)back, since the heavier stone survives with the difference. - If they are equal, push nothing, because both stones are destroyed.
- After the loop, return
-heap[0]if a stone remains, otherwise return 0.
Step-by-step example
stones = [2,7,4,1,8,1]
- Smash the two heaviest, 8 and 7. They differ, so a stone of weight 1 goes back. The stones are now 4, 2, 1, 1, 1.
- Smash 4 and 2. A stone of weight 2 goes back, leaving 2, 1, 1, 1.
- Smash 2 and 1. A stone of weight 1 goes back, leaving 1, 1, 1.
- Smash 1 and 1. They are equal, so both are destroyed and nothing is pushed, leaving a single 1.
- Only one stone remains, so the loop stops and the answer is 1.
Code: Python, Java, C++
1class Solution:
2 def lastStoneWeight(self, stones: List[int]) -> int:
3 # Convert to max heap (negate values)
4 heap = [-s for s in stones]
5 heapq.heapify(heap)
6
7 while len(heap) > 1:
8 first = -heapq.heappop(heap)
9 second = -heapq.heappop(heap)
10 if first != second:
11 heapq.heappush(heap, -(first - second))
12
13 return -heap[0] if heap else 01class Solution {
2 public int lastStoneWeight(int[] stones) {
3 PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
4 for (int s : stones) heap.add(s);
5
6 while (heap.size() > 1) {
7 int first = heap.poll();
8 int second = heap.poll();
9 if (first != second) {
10 heap.add(first - second);
11 }
12 }
13
14 return heap.isEmpty() ? 0 : heap.peek();
15 }
16}1class Solution {
2public:
3 int lastStoneWeight(vector<int>& stones) {
4 priority_queue<int> heap(stones.begin(), stones.end());
5
6 while (heap.size() > 1) {
7 int first = heap.top(); heap.pop();
8 int second = heap.top(); heap.pop();
9 if (first != second) {
10 heap.push(first - second);
11 }
12 }
13
14 return heap.empty() ? 0 : heap.top();
15 }
16};Time and space complexity
O(n log n)
Heapify is O(n). There are at most n - 1 rounds, and each does two pops and at most one push, each O(log n), for O(n log n) total.
O(n)
The heap is a negated copy of the input, so it holds up to n values.
Other approaches
Sort every round (time O(n² log n), space O(n))
Sort the list, take the last two elements, and append the difference if it is not zero, repeating until at most one stone remains. It needs no heap but resorts the list each round.
Bucket counting (time O(n + W), space O(W))
Since weights are small (at most 1000), keep a count array indexed by weight and walk it from the top, smashing stones as you go. This avoids comparisons entirely and is linear in n plus the maximum weight.
Common mistakes
- Using
heapqwithout negating, which pops the two lightest stones instead of the two heaviest. - Forgetting to negate when pushing the difference back, so a positive value lands in a heap of negatives and is treated as the lightest stone.
- Reading
heap[0]when the heap is empty. The final step must check whether any stone survived before reading it. - Looping while the heap is non-empty instead of while it holds more than one stone. With a single stone left, the second
heappopraises an error on an empty heap.
Frequently asked questions
How do you make a max heap in Python?
The heapq module only offers a min heap, so store negated values. Pushing -x and negating the popped value gives max heap behavior with the same O(log n) cost.
What is the time complexity of Last Stone Weight?
With a heap it is O(n log n). Each round removes at least one stone, so there are at most n - 1 rounds, and each round does a constant number of O(log n) heap operations.
Why does the loop stop at one stone?
Smashing needs two stones. Once the heap has one stone or none, no more moves are possible, and the answer is that stone's weight or 0.