InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

Last Stone Weight

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug