Last Stone Weight (LeetCode 1046): Solution and Explanation

Easy
Array
Heap

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Build heap from the negated weights and call heapq.heapify to arrange it in O(n).
  2. While the heap holds more than one stone, pop twice and negate to get the heaviest first and the second heaviest second.
  3. If first != second, push -(first - second) back, since the heavier stone survives with the difference.
  4. If they are equal, push nothing, because both stones are destroyed.
  5. After the loop, return -heap[0] if a stone remains, otherwise return 0.

Step-by-step example

stones = [2,7,4,1,8,1]
  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.
  2. Smash 4 and 2. A stone of weight 2 goes back, leaving 2, 1, 1, 1.
  3. Smash 2 and 1. A stone of weight 1 goes back, leaving 1, 1, 1.
  4. Smash 1 and 1. They are equal, so both are destroyed and nothing is pushed, leaving a single 1.
  5. 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 0

Time and space complexity

Time

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.

Space

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 heapq without 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 heappop raises 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.