LeetCode #1046 Easy

Last Stone Weight

Last Stone Weight is LeetCode 1046 (Easy). You get an array stones of positive weights. Each turn, take the two heaviest stones, y and x with x <= y, and smash them together:

  • If x == y, both stones are destroyed.
  • Otherwise x is destroyed and y becomes y - x.

Repeat until at most one stone is left. Return its weight, or 0 if no stone is left.

Constraints
  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 1000
heapgreedyarray
Open on LeetCode ↗
02

Intuition

Every turn asks the same thing: which stone is heaviest, and which comes next? Then one new stone may join the pile. That is exactly what a max-heap is built for: it hands back the largest item and accepts a new one, each in O(log n).

  • Pop twice: the top two stones are this turn's pair.
  • Push the leftover: if y > x, push y - x; if they are equal, push nothing.
  • Stop at one: each turn removes at least one stone, so there are at most n - 1 turns.

The heap's top is always the true heaviest stone, so the loop follows the rules exactly.

How to spot this pattern

"Keep taking the largest item, then maybe add a new one" is the signal for a max-heap. Connecting ropes, running the biggest job first and this smashing game all have that shape.

03

Approach

Try it first

Before reading on, pick a structure that hands you the heaviest stone quickly even after new stones are added. Then decide what to push back when two stones are equal. Aim for O(n log n).

1

Put every stone in a max-heap

Build a max-heap (the priority queue in C++ and Java) from the whole array in one go, which costs O(n). Python's heapq is a min-heap, so store -w for each weight: the most negative number sits on top, and it belongs to the heaviest stone.

2

Pop the two heaviest stones

While the heap holds two or more stones, pop twice. The first pop is the heavier stone y, so y - x is never negative and needs no abs.

3

Push back only a real leftover

If y != x, push y - x (as -(y - x) in Python). If they are equal, push nothing, since both stones are gone. A pushed 0 would not change the answer, but it would waste a turn smashing against nothing.

4

Return what is left

When the loop ends the heap holds one stone or none. Return that stone's weight, turned back to positive in Python, or 0 when every stone was destroyed.

04

Code in Python, C++ and Java

▶1import heapq
▶2 
▶3class Solution:
▶4 def lastStoneWeight(self, stones):
▶5 heap = [-w for w in stones]
▶6 heapq.heapify(heap)
▶7 while len(heap) > 1:
▶8 y = -heapq.heappop(heap)
▶9 x = -heapq.heappop(heap)
▶10 if y != x:
▶11 heapq.heappush(heap, -(y - x))
▶12 return -heap[0] if heap else 0
stones, heaviest first874211smashheaviest−next=left over6 stones in the heap
heap[8, 7, 4, 2, 1, 1]heaviest first
Every stone goes into a max-heap, so the heaviest one is always on top. The top row lists the stones in the order the heap will hand them out. A heap does not keep the whole list sorted; it only promises the top.
stones, heaviest first74211smash8heaviest−next=left overheaviest is 8 → take it
y8first pop
heap[7, 4, 2, 1, 1]
The first pop gives the heaviest stone, 8. Taking the heavier stone first means the difference below can never be negative.
stones, heaviest first4211smash8heaviest−7next=left overnext heaviest is 7 → take it
x7second pop
heap[4, 2, 1, 1]
The second pop gives the next heaviest, 7. These two are the pair the rules say to smash this turn.
stones, heaviest first42111smash8heaviest−7next=1left overleftover 1 → push it back
y − x1new stone
heap[4, 2, 1, 1, 1]
The weights differ, so the lighter stone is gone and a stone of 1 survives. Pushing it back lets the heap slot it into place, here behind 4, 2, 1, 1, since heavier stones are always handed out first.
stones, heaviest first2111smash4heaviest−next=left overheaviest is 4 → take it
y4first pop
heap[2, 1, 1, 1]
The first pop gives the heaviest stone, 4. Taking the heavier stone first means the difference below can never be negative.
stones, heaviest first111smash4heaviest−2next=left overnext heaviest is 2 → take it
x2second pop
heap[1, 1, 1]
The second pop gives the next heaviest, 2. These two are the pair the rules say to smash this turn.
stones, heaviest first2111smash4heaviest−2next=2left overleftover 2 → push it back
y − x2new stone
heap[2, 1, 1, 1]
The weights differ, so the lighter stone is gone and a stone of 2 survives. Pushing it back lets the heap slot it into place, and it is already the heaviest stone left.
stones, heaviest first111smash2heaviest−next=left overheaviest is 2 → take it
y2first pop
heap[1, 1, 1]
The first pop gives the heaviest stone, 2. Taking the heavier stone first means the difference below can never be negative.
stones, heaviest first11smash2heaviest−1next=left overnext heaviest is 1 → take it
x1second pop
heap[1, 1]
The second pop gives the next heaviest, 1. These two are the pair the rules say to smash this turn.
stones, heaviest first111smash2heaviest−1next=1left overleftover 1 → push it back
y − x1new stone
heap[1, 1, 1]
The weights differ, so the lighter stone is gone and a stone of 1 survives. Pushing it back lets the heap slot it into place, here behind 1, 1, since heavier stones are always handed out first.
stones, heaviest first11smash1heaviest−next=left overheaviest is 1 → take it
y1first pop
heap[1, 1]
The first pop gives the heaviest stone, 1. Taking the heavier stone first means the difference below can never be negative.
stones, heaviest first1smash1heaviest−1next=left overnext heaviest is 1 → take it
x1second pop
heap[1]
The second pop gives the next heaviest, 1. These two are the pair the rules say to smash this turn.
stones, heaviest first1smash1heaviest−1next=0both goneequal weights → both destroyed
y − x0nothing pushed
heap[1]
Equal weights destroy each other, so nothing goes back into the heap. The heap shrinks by two this turn instead of one.
stones, heaviest first1smashheaviest−next=left over1 stone left → return 1
result1
Only one stone remains, so no more smashes are possible. Its weight, 1, is the answer.
05

Common pitfalls

Pushing the leftover without negating it

✗ Wrong
heapq.heappush(heap, y - x)
✓ Right
heapq.heappush(heap, -(y - x))

Every other value in the heap is negative, so a positive leftover reads as a stone of negative weight. On [2,7,4,1,8,1] the function returns -1 instead of 1.

Using Java's default PriorityQueue

✗ Wrong
new PriorityQueue<>()
✓ Right
new PriorityQueue<>(Collections.reverseOrder())

The default queue is a min-heap, so poll() hands out the lightest stones and y - x goes negative. On [2,7,4,1,8,1] the answer comes out as -17.

Reading the top of an empty heap

✗ Wrong
return -heap[0]
✓ Right
return -heap[0] if heap else 0

When the stones cancel out completely, as in [2,2], the heap is empty and heap[0] raises an IndexError. The rules say the answer is 0.

06

Edge cases

A single stone, e.g. [5]

The loop never runs, because the heap starts with one stone. Its weight, 5, is returned as it is.

07

Complexity

Time
O(n log n)
Space
O(n)
Building the heap is O(n). There are at most n - 1 turns, and each does two pops and at most one push at O(log n) each. The priority queue never holds more than n stones.
08

Last Stone Weight FAQ

Can it be solved without a heap?

Yes. With at most 30 stones you can sort the list every turn and smash the last two: O(n² log n), but instant at this size. Since weights are at most 1000, a count array indexed by weight also works, scanning from the heaviest weight down in O(n + 1000). The heap is the version that still scales when the limits grow.

How is it different from Last Stone Weight II?

In Last Stone Weight II (1049) you may smash any two stones, and you want the smallest possible final weight. That turns into splitting the stones into two piles with sums as close as possible, a subset-sum DP. Here the choice is forced (always the two heaviest), so you simply play the game out.