Last Stone Weight

EasyHeapLeetCode 1046 ↗World 9-18
0:00 / 0:00

Smash the two heaviest stones together until at most one is left. A max-heap hands you the two biggest every turn in log time.

▼

The problem

LeetCode 1046 (Easy). You have a pile of stones with positive integer weights. Each turn, take the two heaviest, x ≤ y, and smash them together: if x = y both are destroyed, otherwise x is destroyed and y becomes y − x. When at most one stone is left, return its weight, or 0 if none are left.

Example (LeetCode's): [2,7,4,1,8,1] → 1 (8 and 7 leave 1, 4 and 2 leave 2, 2 and 1 leave 1, then 1 and 1 are both destroyed and one stone of weight 1 is left).

TRY IT ON LEETCODE ▶

The solution

import heapq

def last_stone_weight(stones):
    heap = [-s for s in stones]   # max-heap
    heapq.heapify(heap)
    while len(heap) > 1:
        y = -heapq.heappop(heap)  # heaviest
        x = -heapq.heappop(heap)  # next one
        if y != x:
            heapq.heappush(heap, -(y - x))
    return -heap[0] if heap else 0

Transcript

Last Stone Weight. You get a pile of stones, each with a weight. Each turn, smash the two heaviest together. If they weigh the same, both are destroyed. If not, the lighter one is destroyed, and the heavier one loses that much weight. When one stone or none is left, return its weight, or zero.

Take stones two, seven, four, one, eight, one. Eight and seven are the heaviest: smash, and a one is left. Then four and two leave a two. Two and one leave a one. Now it's all ones. One and one destroy each other, leaving a single stone. The answer is one.

The rules are easy. The work is finding the two heaviest, turn after turn. Sorting the whole pile every turn costs n log n, up to n times. Even scanning for the top two costs order n per turn, so order n squared overall.

We want a pile that always keeps its heaviest stone on top: a max heap. Every stone sits above lighter ones. Pop the top, and a stone from the bottom takes its place, then sinks one level at a time. A pushed stone climbs one level at a time. Either way, about log n steps.

Python's heapq is a min heap, so store negative weights: the heaviest stone becomes the smallest number. Heapify the list. While two or more stones remain, pop the heaviest, then the next heaviest. If they differ, push back the difference. At the end, return the last stone, or zero.

Let's run it. Heapify, and eight rises to the top. Pop eight and seven, push back one. Pop four and two, push back two. Pop two and one, push back one. Pop one and one: they're equal, so nothing goes back. One stone is left, weighing one.

Each turn destroys at least one stone, so there are at most n turns, and each pop or push costs log n. That's order n log n time, and order n space for the heap.

Pop the two heaviest, push back the difference. That's Last Stone Weight.