Last Stone Weight

Smash the two heaviest stones together repeatedly.

Pattern

Max-Heap Simulation

This problem follows the Max-Heap Simulation pattern, commonly found in the Heap / Priority Queue category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Use a max-heap. Pop two largest, push the difference if non-zero.

Key Insight

Python only has min-heaps — negate values to simulate a max-heap. The greedy approach of always smashing the two heaviest is provably optimal.

Step-by-step

  1. 1Insert all stones into a max-heap
  2. 2While the heap has more than one stone:
  3. 3Pop the two heaviest stones
  4. 4If they differ, push the difference back
  5. 5Return the last stone (or 0 if empty)

Pseudocode

heap = [-s for s in stones]  # negate for max-heap
heapify(heap)
while len(heap) > 1:
    a = -heappop(heap)
    b = -heappop(heap)
    if a != b:
        heappush(heap, -(a - b))
return -heap[0] if heap else 0
Complexity Analysis

Time Complexity

O(n log n)

Space Complexity

O(n)
More Heap / Priority Queue Problems

Master this pattern with YeetCode

Practice Last Stone Weight and similar Heap / Priority Queue problems with flashcards. Build pattern recognition through active recall.

Practice this problem