15% off all plans & roadmaps Use code
See plansLast Stone Weight
- LeetCode 1046
- Easy
- Heap (Priority Queue) Patterns
- Top K Elements (Selection/Frequency)
Updated
TL;DR: Repeatedly smash the two heaviest stones and put any remainder back. A max-heap hands you the two heaviest stones in O(log n), so the whole game runs in O(n log n).
Problem
You are given an integer array stones, where stones[i] is the weight of the ith stone.
You play a game with the stones. On each turn, pick the two heaviest stones and smash them together. Say their weights are x and y with x <= y. The smash has one of two outcomes:
- If
x == y, both stones are destroyed. - If
x != y, the stone of weightxis destroyed, and the stone of weightynow has weighty - x.
The game ends when at most one stone is left. Return the weight of the last remaining stone, or 0 if no stones remain.
Example 1
Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: Smash 7 and 8 to get 1, so the array becomes [2,4,1,1,1]. Smash 2 and 4 to get 2, so it becomes [2,1,1,1]. Smash 2 and 1 to get 1, so it becomes [1,1,1]. Smash 1 and 1 to get 0, so it becomes [1]. The last stone weighs 1.
Example 2
Input: stones = [1] Output: 1
Constraints
1 <= stones.length <= 301 <= stones[i] <= 1000
Constraints that matter
stones.length <= 30means even an O(n^2 log n) simulation passes on LeetCode, so the interview value is in showing you know the better structure.- Every smash removes at least one stone, so there are at most n - 1 rounds. That bounds the work per round you can afford.
stones[i] <= 1000allows a counting array of 1001 buckets, which is a valid alternative to a heap.- All weights are positive and a smash result of 0 is dropped, so the heap never holds zeros and an empty heap means the answer is 0.
stones.length >= 1, so you never face an empty input, but the game itself can still end with zero stones.
Hints
Hint 1
The problem asks for the maximum of a changing collection, over and over.
Hint 2
Simulate the game exactly as written.
Solution
Intuition
The problem asks for the maximum of a changing collection, over and over. Each round you remove the two largest values and possibly insert one new value. Any time you see repeated "give me the largest, then update the set", think of a heap (priority queue).
Picture a pile of stones where only the heaviest one is guaranteed to sit on top. The heap is that pile: popping takes the top stone, and pushing drops the remainder back in at its weight-based spot.
Each round changes the collection very little. You remove two items and add at most one. Sorting the whole array again after each round redoes almost all of the earlier work, because the rest of the order has not changed.
A max-heap keeps only enough order to answer one question fast: which element is largest. Pop gives you the largest in O(log n), and push places the new remainder in O(log n). You never pay for a full sort.
The game has no choices. The rule says to take the two heaviest stones, so a correct simulation of the rule is a correct answer. The only design question is how cheaply you can find those two stones each round.
Worked example
Input: stones = [2, 7, 4, 1, 8, 1] Output: 1 Explanation: The game takes four smashes: 8 and 7 leave 1, 4 and 2 leave 2, 2 and 1 leave 1, and the last pair of 1s cancel. One stone of weight 1 is left, so the answer is 1.
Approach 1: Brute force: re-sort every round
Simulate the game exactly as written. At the start of each round, sort the whole array so the two heaviest stones sit at the end. Remove them, and if their weights differ, append the difference.
This is the version a beginner writes first. It is correct, and with n up to 30 it is fast enough, but it does far more ordering work than the problem needs.
Steps
- Copy the input so you do not modify the caller's array.
- While more than one stone remains, sort the array in ascending order.
- Remove the last two elements as
y(heaviest) andx(second heaviest). - If
x != y, appendy - xto the array. - When the loop ends, return the single element if one remains, otherwise 0.
Dry run
Start with [2, 7, 4, 1, 8, 1].
- Round 1: sort to
[1, 1, 2, 4, 7, 8]. Remove 8 and 7, append 1. Array is[1, 1, 2, 4, 1]. - Round 2: sort to
[1, 1, 1, 2, 4]. Remove 4 and 2, append 2. Array is[1, 1, 1, 2]. - Round 3: sort to
[1, 1, 1, 2]. Remove 2 and 1, append 1. Array is[1, 1, 1]. - Round 4: sort again. Remove 1 and 1, append nothing. Array is
[1].
One stone is left with weight 1, which matches the expected output.
Complexity
| Time | O(n^2 log n) |
|---|---|
| Space | O(n) |
Let n be the number of stones. Each round removes at least one stone, so there are at most n - 1 rounds. Each round sorts at most n elements, which costs O(n log n), giving O(n^2 log n) in total. The copy of the input holds n elements, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
pile = list(stones)
while len(pile) > 1:
pile.sort()
y = pile.pop() # heaviest
x = pile.pop() # second heaviest
if x != y:
pile.append(y - x)
return pile[0] if pile else 0
JavaTested in our runner
import java.util.*;
class Solution {
public int lastStoneWeight(int[] stones) {
List<Integer> pile = new ArrayList<>();
for (int s : stones) pile.add(s);
while (pile.size() > 1) {
Collections.sort(pile);
int y = pile.remove(pile.size() - 1);
int x = pile.remove(pile.size() - 1);
if (x != y) pile.add(y - x);
}
return pile.isEmpty() ? 0 : pile.get(0);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
vector<int> pile = stones;
while (pile.size() > 1) {
sort(pile.begin(), pile.end());
int y = pile.back(); pile.pop_back();
int x = pile.back(); pile.pop_back();
if (x != y) pile.push_back(y - x);
}
return pile.empty() ? 0 : pile[0];
}
};
JavaScriptTested in our runner
var lastStoneWeight = function(stones) {
const pile = stones.slice();
while (pile.length > 1) {
pile.sort((a, b) => a - b);
const y = pile.pop();
const x = pile.pop();
if (x !== y) pile.push(y - x);
}
return pile.length ? pile[0] : 0;
};
GoTested in our runner
import "sort"
func lastStoneWeight(stones []int) int {
pile := append([]int(nil), stones...)
for len(pile) > 1 {
sort.Ints(pile)
n := len(pile)
y, x := pile[n-1], pile[n-2]
pile = pile[:n-2]
if x != y {
pile = append(pile, y-x)
}
}
if len(pile) == 0 {
return 0
}
return pile[0]
}
C#Tested in our runner
using System.Collections.Generic;
public class Solution {
public int lastStoneWeight(int[] stones) {
var pile = new List<int>(stones);
while (pile.Count > 1) {
pile.Sort();
int y = pile[pile.Count - 1];
int x = pile[pile.Count - 2];
pile.RemoveRange(pile.Count - 2, 2);
if (x != y) pile.Add(y - x);
}
return pile.Count == 0 ? 0 : pile[0];
}
}
Approach 2: Sorted array with binary-search insertion
What's slow: the brute force sorts the whole array every round, yet only one new value appears. The other elements are already in order, so almost all of that sorting is wasted.
The insight that fixes it: sort once at the start. After each smash, find where the new remainder belongs with binary search and insert it there. Taking the two heaviest stones is then an O(1) removal from the end.
Steps
- Sort a copy of the input in ascending order once.
- While more than one stone remains, remove the last two elements as
yandx. - If
x == y, move on to the next round with nothing to insert. - Otherwise compute
d = y - xand binary-search the sorted array for the position ofd. - Insert
dat that position so the array stays sorted. - Return the single element, or 0 if the array is empty.
Dry run
Sort once: [1, 1, 2, 4, 7, 8].
- Remove 8 and 7, remainder 1. Binary search puts 1 after the existing 1s:
[1, 1, 1, 2, 4]. - Remove 4 and 2, remainder 2. Insert at the end:
[1, 1, 1, 2]. - Remove 2 and 1, remainder 1. Insert after the 1s:
[1, 1, 1]. - Remove 1 and 1, remainder 0. Nothing inserted:
[1].
The answer is 1. No round needed another sort.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Let n be the number of stones. The initial sort costs O(n log n). There are at most n - 1 rounds. Each round does an O(log n) binary search plus an insertion that shifts up to n elements, so O(n) per round and O(n^2) overall. The array holds at most n elements, so space is O(n).
PythonTested in our runner
import bisect
from typing import List, Optional
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
pile = sorted(stones)
while len(pile) > 1:
y = pile.pop()
x = pile.pop()
if x != y:
bisect.insort(pile, y - x) # keeps the list sorted
return pile[0] if pile else 0
JavaTested in our runner
import java.util.*;
class Solution {
public int lastStoneWeight(int[] stones) {
List<Integer> pile = new ArrayList<>();
for (int s : stones) pile.add(s);
Collections.sort(pile);
while (pile.size() > 1) {
int y = pile.remove(pile.size() - 1);
int x = pile.remove(pile.size() - 1);
if (x != y) {
int d = y - x;
int pos = Collections.binarySearch(pile, d);
if (pos < 0) pos = -pos - 1; // insertion point when absent
pile.add(pos, d);
}
}
return pile.isEmpty() ? 0 : pile.get(0);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
vector<int> pile = stones;
sort(pile.begin(), pile.end());
while (pile.size() > 1) {
int y = pile.back(); pile.pop_back();
int x = pile.back(); pile.pop_back();
if (x != y) {
int d = y - x;
pile.insert(lower_bound(pile.begin(), pile.end(), d), d);
}
}
return pile.empty() ? 0 : pile[0];
}
};
JavaScriptTested in our runner
var lastStoneWeight = function(stones) {
const pile = stones.slice().sort((a, b) => a - b);
while (pile.length > 1) {
const y = pile.pop();
const x = pile.pop();
if (x !== y) {
const d = y - x;
let lo = 0, hi = pile.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (pile[mid] < d) lo = mid + 1;
else hi = mid;
}
pile.splice(lo, 0, d);
}
}
return pile.length ? pile[0] : 0;
};
GoTested in our runner
import "sort"
func lastStoneWeight(stones []int) int {
pile := append([]int(nil), stones...)
sort.Ints(pile)
for len(pile) > 1 {
n := len(pile)
y, x := pile[n-1], pile[n-2]
pile = pile[:n-2]
if x != y {
d := y - x
i := sort.SearchInts(pile, d)
pile = append(pile, 0)
copy(pile[i+1:], pile[i:])
pile[i] = d
}
}
if len(pile) == 0 {
return 0
}
return pile[0]
}
C#Tested in our runner
using System.Collections.Generic;
public class Solution {
public int lastStoneWeight(int[] stones) {
var pile = new List<int>(stones);
pile.Sort();
while (pile.Count > 1) {
int y = pile[pile.Count - 1];
int x = pile[pile.Count - 2];
pile.RemoveRange(pile.Count - 2, 2);
if (x != y) {
int d = y - x;
int pos = pile.BinarySearch(d);
if (pos < 0) pos = ~pos; // bitwise complement gives the insertion point
pile.Insert(pos, d);
}
}
return pile.Count == 0 ? 0 : pile[0];
}
}

Solution pattern
Top K Elements (Selection/Frequency)
Part of Heap (Priority Queue) Patterns
Approach 3: Max-heapOptimalTop K Elements (Selection/Frequency)
What's slow: the sorted array still shifts up to n elements on every insertion. You keep a full ordering of all stones, but you only ever look at the top two.
The insight that fixes it: a max-heap keeps only the order needed to find the largest item. Pop and push both cost O(log n), with no shifting. Build the heap once, then pop two, push the remainder, and repeat.
Python's heapq is a min-heap, so store negated weights. Java needs Collections.reverseOrder(). C++ priority_queue is already a max-heap.
Steps
- Put every stone weight into a max-heap.
- While the heap holds more than one stone, pop the top as
y. - Pop the next top as
x. It is the second heaviest. - If
x != y, pushy - xback into the heap. - After the loop, return 0 if the heap is empty.
- Otherwise return the one stone left in the heap.
Dry run
Heap contents are shown as a multiset, largest first.
| Step | Pop y | Pop x | Push | Heap after |
|---|---|---|---|---|
| start | {8, 7, 4, 2, 1, 1} | |||
| 1 | 8 | 7 | 1 | {4, 2, 1, 1, 1} |
| 2 | 4 | 2 | 2 | {2, 1, 1, 1} |
| 3 | 2 | 1 | 1 | {1, 1, 1} |
| 4 | 1 | 1 | none | {1} |
The heap now has one stone, so the loop stops. The answer is 1.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the number of stones. Building the heap costs O(n) with heapify, or O(n log n) with repeated pushes. Each round pops twice and pushes at most once, so it does at most three O(log n) operations. There are at most n - 1 rounds, which gives O(n log n) in total. The heap never holds more than n stones, so space is O(n).
PythonTested in our runner
import heapq
from typing import List, Optional
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
heap = [-s for s in stones] # negate: heapq is a min-heap
heapq.heapify(heap)
while len(heap) > 1:
y = -heapq.heappop(heap) # heaviest
x = -heapq.heappop(heap) # second heaviest
if x != y:
heapq.heappush(heap, -(y - x))
return -heap[0] if heap else 0
JavaTested in our runner
import java.util.*;
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int s : stones) heap.add(s);
while (heap.size() > 1) {
int y = heap.poll();
int x = heap.poll();
if (x != y) heap.add(y - x);
}
return heap.isEmpty() ? 0 : heap.peek();
}
}
C++Tested in our runner
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> heap(stones.begin(), stones.end()); // max-heap
while (heap.size() > 1) {
int y = heap.top(); heap.pop();
int x = heap.top(); heap.pop();
if (x != y) heap.push(y - x);
}
return heap.empty() ? 0 : heap.top();
}
};
JavaScriptTested in our runner
var lastStoneWeight = function(stones) {
// JavaScript has no built-in heap, so keep a small array-based max-heap.
const heap = [];
const push = (v) => {
heap.push(v);
let i = heap.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (heap[p] >= heap[i]) break;
[heap[p], heap[i]] = [heap[i], heap[p]];
i = p;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
const n = heap.length;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < n && heap[l] > heap[m]) m = l;
if (r < n && heap[r] > heap[m]) m = r;
if (m === i) break;
[heap[m], heap[i]] = [heap[i], heap[m]];
i = m;
}
}
return top;
};
for (const s of stones) push(s);
while (heap.length > 1) {
const y = pop();
const x = pop();
if (x !== y) push(y - x);
}
return heap.length ? heap[0] : 0;
};
GoTested in our runner
import "container/heap"
type maxHeap []int
func (h maxHeap) Len() int { return len(h) }
func (h maxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h maxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *maxHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *maxHeap) Pop() interface{} {
old := *h
n := len(old)
v := old[n-1]
*h = old[:n-1]
return v
}
func lastStoneWeight(stones []int) int {
h := maxHeap(append([]int(nil), stones...))
heap.Init(&h)
for h.Len() > 1 {
y := heap.Pop(&h).(int)
x := heap.Pop(&h).(int)
if x != y {
heap.Push(&h, y-x)
}
}
if h.Len() == 0 {
return 0
}
return h[0]
}
C#Tested in our runner
using System.Collections.Generic;
public class Solution {
public int lastStoneWeight(int[] stones) {
// PriorityQueue is a min-heap on priority, so use the negated weight.
var heap = new PriorityQueue<int, int>();
foreach (int s in stones) heap.Enqueue(s, -s);
while (heap.Count > 1) {
int y = heap.Dequeue();
int x = heap.Dequeue();
if (x != y) {
int d = y - x;
heap.Enqueue(d, -d);
}
}
return heap.Count == 0 ? 0 : heap.Peek();
}
}
Common mistakes
- Returning
heap[0]in Python without negating it. The heap stores-weight, so the answer is-heap[0]. Negate on the way out, as you negate on the way in. - Reading
heap[0],heap.peek()orheap.top()without an emptiness check. When the last two stones are equal, the heap is empty and the call fails or reads garbage. Return0explicitly when the heap is empty. - Pushing
y - xwhenx == y. A zero-weight stone looks like a real stone and inflates the count, so the loop runs an extra round. Push only whenx != y. - Sorting once and then popping from the end without re-inserting the remainder in order. The new value
y - xcan belong anywhere in the array, so the next round picks the wrong stones. Either re-sort, binary-insert, or use a heap. - Using a min-heap with plain values in Java or Python. You then smash the two lightest stones instead of the two heaviest. Use
Collections.reverseOrder()in Java and negate values in Python. - Subtracting in the wrong order, as in
x - ywhenxis the second pop. The result can be negative and breaks the heap logic. Pop the heaviest first, and computeheaviest - second.
Edge cases
[1]: the loop never runs, and the answer is the single stone, 1.[5, 5]: the two stones cancel, the heap is empty, and the answer is 0.[3, 3, 3]: the first smash destroys two 3s, leaving one 3, so the answer is 3.[2, 2, 2, 2]: two smashes cancel everything, so the answer is 0.[1000, 1]: one smash leaves 999, so the answer is 999.[1, 1, 1, 1, 1](odd count, all equal): two smashes remove four stones and one 1 remains, so the answer is 1.
Follow-ups interviewers ask
- Can you do better than O(n log n) when weights are at most 1000?
- Yes. Use a counting array with 1001 buckets indexed by weight. Walk a pointer down from the largest weight. When a bucket holds two or more stones, they cancel in pairs. When it holds one, find the next non-empty bucket below it, smash, and add the remainder to its bucket. The pointer only moves downward except for inserts, so the total is bounded by O(n + W) on this problem's sizes, where W is the max weight. That is linear in n for fixed W.
- What if n is large, like 10^6 stones?
- The re-sort solution is too slow at O(n^2 log n) and the binary-insertion version at O(n^2) is also too slow. The heap solution does about 3n heap operations of O(log n) each, so it handles 10^6 stones comfortably. With small bounded weights, the bucket method is faster still.
- Can you solve it with O(1) extra space?
- Only by reusing the input. Heapify the input array in place and run the same loop, shrinking the logical heap size as stones are removed. That uses O(1) extra space but destroys the caller's array. If you must preserve the input, you need an O(n) copy.
Last Stone Weight FAQ
What is the time complexity of Last Stone Weight?
The max-heap solution runs in O(n log n) time, where n is the number of stones. There are at most n - 1 rounds, and each round does two pops and at most one push, each O(log n). Space is O(n) for the heap.
Why use a max-heap for Last Stone Weight?
Each round needs the two largest stones, and the set changes by one insertion after every smash. A max-heap returns the largest in O(log n) and accepts a new value in O(log n). Re-sorting the array each round costs O(n log n) instead.
How do you solve Last Stone Weight in Python?
Negate every weight and store it in a heapq list, because heapq is a min-heap. Pop twice, negate the results to get y and x, and push -(y - x) if the stones differ. Return -heap[0] if the heap is non-empty, otherwise 0.
How do you solve Last Stone Weight in Java?
Create a PriorityQueue<Integer> with Collections.reverseOrder() so it behaves as a max-heap. Poll twice, add y - x when they differ, and finish with heap.isEmpty() ? 0 : heap.peek(). The poll calls cannot return null inside the loop because the size is above 1.
Is sorting enough for LeetCode 1046?
With n at most 30, re-sorting each round passes the tests. It still costs O(n^2 log n) and shows the repeated work an interviewer will ask you to remove. Sorting once and binary-inserting gives O(n^2), and the heap gives O(n log n).
Is Last Stone Weight II the same problem?
No. Last Stone Weight II lets you pick any two stones, not the heaviest two, and asks for the smallest possible leftover weight. It becomes a subset-sum style dynamic programming problem, so a heap does not apply.
Asked at
See which companies ask this — Pro
Related problems
- Kth Largest Element in a Stream · same technique: Top K Elements (Selection/Frequency)
- Relative Ranks · same technique: Top K Elements (Selection/Frequency)
- Take Gifts From the Richest Pile · same technique: Top K Elements (Selection/Frequency)
- Top K Frequent Elements · same technique: Top K Elements (Selection/Frequency)
- Kth Largest Element in an Array · same technique: Top K Elements (Selection/Frequency)
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Design Twitter · same pattern: Heap (Priority Queue) Patterns
- K Closest Points to Origin · same pattern: Heap (Priority Queue) Patterns
- Reorganize String · same pattern: Heap (Priority Queue) Patterns
- Single-Threaded CPU · same pattern: Heap (Priority Queue) Patterns