Last Stone Weight solution explained
Last Stone Weight is solved with a max-heap. Put every weight in the heap, then repeatedly pop the two heaviest stones, push back their difference if it is not zero, and stop when one stone or none is left. Each round costs O(log n) and there are at most n - 1 rounds, so the whole simulation runs in O(n log n).
By Evin JohnPublished 7 min read
The problem in plain terms
You have a pile of stones, each with a positive integer weight. On every turn you pick the two heaviest. If they weigh the same, both are destroyed. If not, the lighter one is destroyed and the heavier one loses exactly the lighter one's weight, then goes back into the pile. When the pile holds one stone, return that stone's weight. When it is empty, return 0.
| Stones | Answer | Why |
|---|---|---|
| [3, 9, 4, 4] | 2 | 9 and 4 leave 5; 5 and 4 leave 1; 3 and 1 leave 2 |
| [6, 6] | 0 | Equal stones destroy each other and the pile is empty |
| [10] | 10 | Nothing to smash |
| [5, 5, 5] | 5 | Two fives cancel, one five is left over |
| [12, 3, 8, 1, 5] | 1 | 12 and 8 leave 4; 5 and 4 leave 1; 3 and 1 leave 2; 2 and 1 leave 1 |
Before coding, check two things with the interviewer: whether an empty input is possible (return 0 if so), and whether weights can be zero. Zero weights do not break either solution, but asking shows you read the input rules instead of assuming them.
Why interviewers use it
This is a warm-up question for heaps. There is no trick to discover: the rules already say what to do. What the interviewer watches is whether you recognize that the same operation, find the two largest values, repeats on a collection that keeps changing, and whether you reach for the data structure built for that. It also checks language fluency, because Python has no max-heap and the negation trick trips people up under pressure.
Follow-ups you may hear
- What if you may choose any two stones, and want the smallest possible final weight? That is a different problem. It becomes a partition question: split the stones into two groups with sums as close as possible, solved with a subset-sum dynamic program. Greedy smashing does not give the minimum there.
- Weights are small integers, say below a few thousand. An array of counts indexed by weight can stand in for the heap. Mention it as an option; the heap is the expected answer.
- Return the order of smashes, not only the result. Record each popped pair before pushing the difference.
- Stones arrive while you are smashing. A heap handles inserts at any time in O(log n), which is exactly why it beats re-sorting.
First pass: sort before every smash
The literal reading of the rules: sort the pile, take the last two, push back the difference, repeat. It is a good thing to say out loud first because it is obviously correct. Each sort is O(n log n) and there can be up to n - 1 rounds, which gives O(n² log n). Inserting the difference into the right place in an already sorted list would bring it to O(n²), still quadratic.
def last_stone_by_sorting(stones):
pile = list(stones)
while len(pile) > 1:
pile.sort()
heaviest = pile.pop()
runner_up = pile.pop()
if heaviest != runner_up:
pile.append(heaviest - runner_up)
return pile[0] if pile else 0The heap solution
A max-heap keeps the largest value at the root and restores that property in O(log n) after every pop or push. Building it from the list takes O(n). Each round then pops twice and maybe pushes once. Every round removes at least one stone for good, so the loop runs at most n - 1 times. Python's heapq module only provides a min-heap, so store each weight as its negative: the most negative entry is the heaviest stone.
import heapq
def last_stone_weight(stones):
# heapq only offers a min-heap, so weights are stored negated
heap = [-w for w in stones]
heapq.heapify(heap)
while len(heap) > 1:
big = -heapq.heappop(heap)
next_big = -heapq.heappop(heap)
if big != next_big:
heapq.heappush(heap, -(big - next_big))
return -heap[0] if heap else 0The push stores -(big - next_big). Writing next_big - big gives the same number and some people prefer it, but say which one you mean, because a sign slip here produces a positive value in a heap of negatives and the answer quietly goes wrong.
#include <queue>
#include <vector>
int lastStoneWeight(const std::vector<int>& stones) {
// std::priority_queue is a max-heap unless told otherwise
std::priority_queue<int> heap(stones.begin(), stones.end());
while (heap.size() > 1) {
int big = heap.top();
heap.pop();
int nextBig = heap.top();
heap.pop();
if (big != nextBig) heap.push(big - nextBig);
}
return heap.empty() ? 0 : heap.top();
}Constructing the priority_queue from the iterator range builds the heap in linear time, the same as heapify. In C++ you must read top() before pop(), because pop() returns nothing.
Cost of each approach
| Approach | Time | Extra space | Comment |
|---|---|---|---|
| Sort every round | O(n² log n) | O(n) or O(1) in place | Fine to mention, not to submit |
| Sorted list with binary insert | O(n²) | O(n) | Insertion shifts elements |
| Max-heap | O(n log n) | O(n) | The expected answer |
Edge cases to test
- Empty pile: return 0 rather than reading from an empty heap.
- One stone: return it without entering the loop.
- Two equal stones: the pile ends empty, so the answer is 0.
- An odd number of equal stones, such as [5, 5, 5]: one survives.
- A remainder that becomes the new heaviest stone, as when 12 and 8 leave 4 in the example above. The heap handles it; a two-pointer idea on a sorted list does not.
Where candidates slip
- Using heapq as if it were a max-heap and smashing the two lightest stones.
- Negating on the way in but forgetting to negate on the way out, so the function returns -2 instead of 2.
- Pushing back a zero when the stones are equal. It does not change the result here, but it adds pointless work and shows the rules were not read closely.
- Calling heap[0] or top() on an empty structure at the end.
- Re-sorting inside the loop and then claiming O(n log n).
How to talk through it
Fictional example
- Candidate
- Every turn needs the two largest weights from a pile that keeps changing, so I want a max-heap rather than sorting again and again.
- Candidate
- Python only has a min-heap, so I'll store negatives. I heapify in linear time, then loop while at least two stones remain: pop two, and if they differ, push the difference back.
- Candidate
- Each round removes at least one stone, so there are at most n minus one rounds at log n each. If the heap is empty at the end I return zero.
- Interviewer
- And if you could pick any two stones?
- Candidate
- Then greedy is no longer optimal. I'd treat it as splitting the stones into two groups with sums as close as possible, which is a subset-sum DP.
Related problems
The same heap habit appears in Kth Largest Element in an Array, where a small heap keeps only the values that matter, and in K Closest Points to Origin, which ranks points by distance instead of weight. Task Scheduler also pops the largest count, runs it, and pushes it back later. For counting before selecting, see Top K Frequent Elements. The coding problems hub lists the rest.
Practicing with Natively
Natively runs on Mac and Windows and can read a practice problem from a screenshot, then lay out an approach and code in its overlay, which is handy when you want to check whether your heap version matches a second opinion. If you rehearse out loud, its live transcript lets you check afterward whether you mentioned the negation trick and the complexity before writing code. See how Natively helps with coding interviews.
Questions people ask
What is the best approach for Last Stone Weight?
A max-heap. Pop the two heaviest stones, push back their difference if it is not zero, and repeat until at most one stone remains. It runs in O(n log n) time with O(n) space.
How do you make a max-heap in Python for Last Stone Weight?
heapq is a min-heap, so push each weight as a negative number. The smallest stored value is then the heaviest stone. Negate values again when you pop them and when you return the answer.
What does Last Stone Weight return when no stones are left?
It returns 0. That happens when the last two stones weigh the same, or when the input is empty, if your version allows that.
How is Last Stone Weight II different?
In the second version you may smash any two stones, and you want the smallest possible final weight. Greedy no longer works; it becomes a partition problem solved with a subset-sum dynamic program.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
