Last Stone Weight - Problem

Imagine you're playing an ancient stone-smashing game! You have a collection of stones, each with a specific weight, and you need to repeatedly smash the two heaviest stones together until at most one stone remains.

Here's how the game works:

  • ๐ŸŽฏ Choose the two heaviest stones (let's call their weights x and y where x โ‰ค y)
  • ๐Ÿ’ฅ Smash them together:
    • If x == y: Both stones are completely destroyed
    • If x < y: The lighter stone is destroyed, and the heavier stone becomes a new stone with weight y - x
  • ๐Ÿ”„ Repeat until there's at most one stone left

Goal: Return the weight of the last remaining stone, or 0 if no stones are left.

Example: Stones [2,7,4,1,8,1] โ†’ After all smashing โ†’ Last stone weighs 1

Input & Output

example_1.py โ€” Standard Case
$ Input: [2,7,4,1,8,1]
โ€บ Output: 1
๐Ÿ’ก Note: Step by step: [2,7,4,1,8,1] โ†’ smash 8,7 โ†’ [2,4,1,1,1] โ†’ smash 4,2 โ†’ [2,1,1,1] โ†’ smash 2,1 โ†’ [1,1,1] โ†’ smash 1,1 โ†’ [1] โ†’ final answer: 1
example_2.py โ€” Single Stone
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: Only one stone exists, so no smashing occurs. The weight of the last (and only) stone is 1.
example_3.py โ€” All Stones Destroyed
$ Input: [3,3]
โ€บ Output: 0
๐Ÿ’ก Note: Both stones have equal weight (3), so when they smash together, both are completely destroyed. No stones remain, so return 0.

Visualization

Tap to expand
Stone Tournament - Max Heap VisualizationRound 1: Champions 8 vs 787๐Ÿ’ฅ Battle Result: 8-7=1Waiting Fighters:4211Round 2: New Champion 4 vs 2421From R1๐Ÿ’ฅ Battle Result: 4-2=2Remaining:11Final: Last Stone Standing1๐Ÿ† Tournament Winner!
Understanding the Visualization
1
Tournament Setup
All fighters (stones) enter the tournament bracket, arranged by strength
2
Championship Match
The two strongest fighters face off in the center ring
3
Battle Result
Either both are eliminated (equal strength) or winner continues with reduced power
4
New Champion
The surviving fighter rejoins the tournament, and the process repeats
Key Takeaway
๐ŸŽฏ Key Insight: A max heap maintains the tournament bracket automatically, always keeping the strongest fighters (heaviest stones) ready for the next battle without expensive reorganization.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

Building heap takes O(n log n), and each of the n operations takes O(log n) time

n
2n
โšก Linearithmic
Space Complexity
O(n)

The heap stores all stones, requiring O(n) extra space

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค stones.length โ‰ค 30
  • 1 โ‰ค stones[i] โ‰ค 1000
  • All stone weights are positive integers
Asked in
Amazon 45 Google 32 Meta 28 Microsoft 19
89.4K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen