Try it first — give it 15 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an array stones of positive weights. Each round:
- Take the two heaviest stones,
yandx, withx ≤ y. - Smash them together. If
x == y, both are destroyed. Otherwisexis destroyed andybecomes a stone of weighty − x, which goes back into the pile.
Keep going until at most one stone is left. Return its weight, or 0 if nothing is left. There are at most 30 stones, each weighing between 1 and 1000.
Example: stones = [2, 7, 4, 1, 8, 1] → 1. Smash 8 and 7 → 1 is left, so the pile is [2, 4, 1, 1, 1]. Smash 4 and 2 → [2, 1, 1, 1]. Smash 2 and 1 → [1, 1, 1]. Smash 1 and 1 → [1]. Answer 1.
Start with brute force
Each round, sort the pile, take the last two, and put the difference back.
That's O(n log n) per round. Each round removes at least one stone, so there are at most n − 1 rounds: O(n² log n) overall. With n ≤ 30 that is tiny and it would pass. Be honest about that in an interview. The reason to do better is that the same pattern shows up with n = 10⁵, where n² log n is around 10¹¹.
Building the intuition
Look at what the simulation actually asks for, over and over:
- "What's the heaviest stone?"
- "Remove it."
- "Add this new stone."
Sorting answers the first question, but then you add a stone and the order is broken, so you sort again. You're paying to put every stone in order when you only ever look at the top two.
A heap is the structure that keeps only "who's on top" correct. It is a tree stored in an array where every parent is at least as large as its children (for a max-heap). That weaker rule is cheap to repair: adding or removing one item costs O(log n), not a full re-sort.
So the plan is just to run the simulation the problem describes, using a max-heap as the pile.
The one language trap: Python's heapq and Java's PriorityQueue are min-heaps. The standard Python move is to store -weight, so the heaviest stone becomes the most negative number and pops first. Java takes Collections.reverseOrder(). C++ priority_queue is already a max-heap. JavaScript has no heap at all, so the solution includes a small MinHeap class and stores negatives, exactly like the Python version.
The optimal approach
- Build a max-heap from all the stones.
- While the heap has at least two stones:
- pop
y(heaviest), then popx(second heaviest, sox ≤ y); - if
y != x, pushy − x.
- pop
- Return the remaining stone, or
0if the heap is empty.
The subtle detail is the order of the two pops. The first pop is the larger one. If you compute x − y instead, Python's negated version will happily push a negative weight, and your answer goes wrong without any error.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
import heapq
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
# heapq is a MIN-heap; storing -weight makes the heaviest stone pop first
heap = [-s for s in stones]
heapq.heapify(heap)
while len(heap) > 1:
y = -heapq.heappop(heap) # heaviest
x = -heapq.heappop(heap) # second heaviest, so x <= y
if y != x:
heapq.heappush(heap, -(y - x)) # the leftover piece goes back in
return -heap[0] if heap else 0class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
// priority_queue is a MAX-heap by default: top() is the heaviest stone
priority_queue<int> heap(stones.begin(), stones.end());
while (heap.size() > 1) {
int y = heap.top(); heap.pop(); // heaviest
int x = heap.top(); heap.pop(); // second heaviest, so x <= y
if (y != x) {
heap.push(y - x); // the leftover piece goes back in
}
}
return heap.empty() ? 0 : heap.top();
}
};class Solution {
public int lastStoneWeight(int[] stones) {
// PriorityQueue is a MIN-heap by default; reverseOrder() makes the heaviest come out first
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int s : stones) heap.offer(s);
while (heap.size() > 1) {
int y = heap.poll(); // heaviest
int x = heap.poll(); // second heaviest, so x <= y
if (y != x) {
heap.offer(y - x); // the leftover piece goes back in
}
}
return heap.isEmpty() ? 0 : heap.peek();
}
}// JavaScript has no built-in heap, so we carry a small binary min-heap.
class MinHeap {
constructor() {
this.a = [];
}
size() {
return this.a.length;
}
peek() {
return this.a[0];
}
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) { // bubble up while smaller than the parent
const p = (i - 1) >> 1;
if (a[p] <= a[i]) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last; // move the last leaf to the root, then sink it
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && a[l] < a[m]) m = l;
if (r < a.length && a[r] < a[m]) m = r;
if (m === i) break;
[a[m], a[i]] = [a[i], a[m]];
i = m;
}
}
return top;
}
}
/**
* @param {number[]} stones
* @return {number}
*/
var lastStoneWeight = function (stones) {
// A min-heap of -weight behaves like a max-heap: the heaviest stone pops first
const heap = new MinHeap();
for (const s of stones) heap.push(-s);
while (heap.size() > 1) {
const y = -heap.pop(); // heaviest
const x = -heap.pop(); // second heaviest, so x <= y
if (y !== x) {
heap.push(-(y - x)); // the leftover piece goes back in
}
}
return heap.size() ? -heap.peek() : 0;
};Dry run
stones = [2, 7, 4, 1, 8, 1]
| Round | Heap (as a sorted view) | y | x | Pushed back |
|---|---|---|---|---|
| 1 | 8, 7, 4, 2, 1, 1 | 8 | 7 | 1 |
| 2 | 4, 2, 1, 1, 1 | 4 | 2 | 2 |
| 3 | 2, 1, 1, 1 | 2 | 1 | 1 |
| 4 | 1, 1, 1 | 1 | 1 | nothing (equal) |
| end | 1 | answer 1 |
(The heap doesn't store its items in sorted order; the column just shows what's inside.)
Complexity
- Time: O(n log n). Building the heap is O(n) with heapify (or O(n log n) pushing one by one). Each round removes at least one stone, so there are at most
n − 1rounds, each with O(log n) heap work. - Space: O(n). The heap holds the stones. (C++ and Java copy them; Python builds a new negated list.)
Edge cases and traps
- One stone.
[5]→5. The loop never runs. - Everything cancels.
[3, 3]→0. Return 0 when the heap is empty, don't read its top. - Forgetting the default ordering. A min-heap here smashes the two lightest stones. The code runs and returns a wrong number. Python
heapq: negate. Java:Collections.reverseOrder(). C++: the default is already a max-heap. - Pushing zero. If
y == x, push nothing. Pushing a0stone happens to give the same result here, but it's wrong to the problem's rules and costs an extra round. - Negation sign slips in Python. Pop gives
-y; you needy = -heappop(heap), and you push-(y - x).
Say it in the interview
"This is a straight simulation, and the only question is the data structure. Every round I need the two heaviest stones and then I may add a new one, so a max-heap fits perfectly. I heapify all stones, then while there are at least two I pop y and x, and if they're different I push y minus x back. At the end I return the last stone or zero. Each round is O(log n) and removes at least one stone, so it's O(n log n) overall. In Python I'd negate weights because heapq is a min-heap."
Follow-ups interviewers ask
- "Could you do it without a heap?" Weights are at most 1000, so you can bucket-count weights and walk down from 1000. That's O(n + W), where W is the max weight.
- "What if you could choose any two stones to smash and wanted the smallest possible last stone?" That's a different problem (Last Stone Weight II): split the stones into two groups with sums as close as possible, a knapsack-style DP from the Dynamic Programming stage.
- "What's heapify's cost?" O(n), not O(n log n): most nodes are near the bottom and barely move.
Practise the same idea
This is Day 62 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free