Algorithms · Heaps

Last Stone Weight

Smash the two heaviest stones until one is left.

The problem

Take the two heaviest stones and smash them together. If they weigh the same, both vanish; otherwise a stone weighing the difference is left. Repeat until at most one stone remains, and return its weight (0 if none).

last_stone([2, 7, 4, 1, 8, 1])1
last_stone([1])1
Heaps. Always know the biggest. A hospital waiting room: the most urgent patient is always seen next.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def last_stone(stones):take the stone weights
stones = stones[:]work on a copy
while len(stones) > 1:while two or more stones remain
stones.sort()line them all up, lightest first (every round!)
a = stones.pop()take the heaviest
b = stones.pop()and the next heaviest
if a != b:not the same weight?
stones.append(a - b)the difference is left
return stones[0] if stones else 0what's left

Now ask: what if there were a billion?

Your computer decides which program runs next with a priority queue: a heap of jobs ordered by urgency. It picks the next job thousands of times a second.

Aim for O(n log n)🌱 warm-up

Think it through

Each round, which stones do you need?

  • All of them, sorted
  • Only the two heaviest
Show the answer

Only the two heaviest. Sorting everything every round is a lot of work for two stones. You need something that hands you the biggest quickly and takes one back quickly.

What hands you the biggest item quickly, even as items come and go?

  • A heap
  • A sorted list you re-sort
Show the answer

A heap. A heap gives the top and accepts a new item in about log n steps. Python’s heapq keeps the smallest on top, so store weights as negatives.

Stuck? 3 nudges, smallest first
  1. Each round you only need the two heaviest stones. Sorting everything every round is a lot of extra work.
  2. A heap hands you the biggest item quickly, and lets you add one back quickly.
  3. heapq keeps the smallest on top, so store weights as negatives. heappop twice, heappush the difference.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
import heapqPython's heap tools
def last_stone(stones):take the stone weights
heap = [-s for s in stones]heapq keeps the smallest on top, so store them negative
heapq.heapify(heap)arrange them into a heap
while len(heap) > 1:while two or more stones remain
a = -heapq.heappop(heap)take the heaviest
b = -heapq.heappop(heap)and the next heaviest
if a != b:not the same weight?
heapq.heappush(heap, -(a - b))the difference goes back on the heap
return -heap[0] if heap else 0what's left

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with heaps