Last Stone Weight
Problem
You are given an array stones of stone weights. Each turn, take the two heaviest stones x ≤ y and smash them: if x == y both are destroyed, otherwise x is destroyed and y becomes y - x.
When at most one stone is left, return its weight, or 0 if none are left.
Example 1
- Input
stones = [2, 7, 4, 1, 8, 1]- Output
1- Why
- 8 and 7 → 1; 4 and 2 → 2; 2 and 1 → 1; 1 and 1 → 0; one stone of weight 1 remains.
Example 2
- Input
stones = [1]- Output
1
Constraints
- 1 ≤ stones.length ≤ 30
- 1 ≤ stones[i] ≤ 1000
Explanation
Each turn needs the two largest values, and then a new value goes back in. A max-heap gives both operations in O(log n).
Approach 1 · Naive
Sort every turn
- Time O(n² log n)
- Space O(n)
Sort the list each turn, take the last two, and put the difference back.
- While more than one stone remains: sort, pop the two largest.
- If they differ, append the difference.
import java.util.*;
class Solution {
public int lastStoneWeight(int[] stones) {
List<Integer> list = new ArrayList<>();
for (int stone : stones) {
list.add(stone);
}
while (list.size() > 1) {
Collections.sort(list);
int y = list.remove(list.size() - 1);
int x = list.remove(list.size() - 1);
if (x != y) {
list.add(y - x);
}
}
return list.isEmpty() ? 0 : list.get(0);
}
}class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones = list(stones)
while len(stones) > 1:
stones.sort()
y, x = stones.pop(), stones.pop()
if x != y:
stones.append(y - x)
return stones[0] if stones else 0Approach 2 · Optimal
Max-heap
- Time O(n log n)
- Space O(n)
Keep all stones in a max-heap; pop two, push back the difference.
- Build a max-heap of all stones.
- While it has at least two stones: pop
y, popx; ify > x, pushy - x. - Return the remaining stone, or 0.
import java.util.*;
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int stone : stones) {
heap.offer(stone);
}
while (heap.size() > 1) {
int y = heap.poll();
int x = heap.poll();
if (y > x) {
heap.offer(y - x);
}
}
return heap.isEmpty() ? 0 : heap.peek();
}
}import heapq
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
heap = [-s for s in stones] # heapq is a min-heap, so store negatives
heapq.heapify(heap)
while len(heap) > 1:
y = -heapq.heappop(heap)
x = -heapq.heappop(heap)
if y > x:
heapq.heappush(heap, -(y - x))
return -heap[0] if heap else 0Complexity compared
| Approach | Time | Space |
|---|---|---|
| Naive Sort every turn | O(n² log n) | O(n) |
| Optimal Max-heap | O(n log n) | O(n) |
Key takeaways
- Python's
heapqis a min-heap only; push negated values to get a max-heap.
Your notes
Saved in this browser as you type.
Solved it on your own?
Mark it done to track your progress, or star it to come back before an interview.