Last Stone Weight

25 min · lastStoneWeight()

Imagine a tournament where the two strongest stones collide every round. Equal rivals both disappear; an uneven match sends only their weight difference back into the arena.

You're given the positive weights in stones. Repeatedly choose the two heaviest remaining stones. Call their weights x and y, where x <= y:

  • If x == y, remove both.
  • Otherwise, remove both and add one new stone weighing y - x.

Return the final stone's weight. Return 0 when every stone disappears.

Constraints

  • 1 <= stones.length <= 30_000
  • 1 <= stones[i] <= 1_000

Hints

Model the rules directly

Sort the remaining weights, remove the last two, and put their difference back. That gives you a trustworthy first solution.

Name the repeated expense

You need the two largest values every round, but repeated sorting rebuilds far more order than you use. Which structure keeps its largest value ready?

Turn the arena into a heap

A max-heap is a structure that exposes its largest stored value first. Pop twice, push y - x when it's nonzero, and stop when fewer than two weights remain.

Follow-up

Stone weights never exceed 1,000. Could a frequency table replace the heap, and what would its running time depend on?

Visible cases

Examples

Example 1

ready
Input
stones = [
  2,
  7,
  4,
  1,
  8,
  1
]
Expected
1
Why
the collisions eventually leave one stone weighing 1

Example 2

ready
Input
stones = [
  1,
  1
]
Expected
0
Why
equal heaviest stones destroy each other

Example 3

ready
Input
stones = [
  5
]
Expected
5
Why
one stone is already the final survivor

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite