InterviewPrepKit

Home / Coding / Heap & Priority Queue

Last Stone Weight

easy Original ↗
Solving tips
  • Recognize a priority-queue simulation: each round needs the two largest values, so use a max-heap.
  • Python's heapq is min-only — negate weights on push and pop so the smallest stored value is the heaviest stone.
  • Pop y (heaviest) then x; only push back y - x when y > x, or you seed phantom weight-0 stones.
  • Target O(n log n) time and O(n) space; return 0 (not a crash) when the heap empties on total annihilation.

Problem

You have a pile of stones, each with a positive integer weight, given as an array stones.

Repeat the following until at most one stone remains: take the two heaviest stones, weights x <= y, and smash them together.

  • If x == y, both stones are destroyed.
  • If x < y, the stone of weight x is destroyed and the other stone’s weight becomes y - x.

Return the weight of the last remaining stone, or 0 if none remain.

Examples

  • stones = [2, 7, 4, 1, 8, 1]1. Smash 8 and 7 → 1 remains, pile [2, 4, 1, 1, 1]; smash 4 and 2 → 2, pile [2, 1, 1, 1]; smash 2 and 1 → 1, pile [1, 1, 1]; smash 1 and 1 → both gone, pile [1]. Answer 1.
  • stones = [1]1. A single stone is never smashed.
  • stones = [3, 3]0. Equal stones annihilate each other, leaving nothing.

Constraints

  • 1 <= len(stones) <= 30
  • 1 <= stones[i] <= 1000

Think about it first

Hint 1 Simulate the process literally — the only operation you ever need is "give me the two largest values currently in the pile."
Hint 2 Repeatedly scanning or re-sorting the list to find the two largest works but is quadratic. Which data structure hands you the maximum in O(log n) per extraction?
Hint 3 Python's `heapq` is a min-heap only — store each weight negated so the smallest stored value is the heaviest stone. Pop twice, push back the (negated) difference if nonzero, loop until one or zero items remain.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.