Last Stone Weight
Easy
Topics
You are given stones weights. Each turn, smash the two heaviest together: if equal both are destroyed, else the lighter is destroyed and the heavier becomes their difference. Return the weight of the last remaining stone, or 0 if none remain.
Example 1
Each chip is one smash of the two heaviest stones. Final weight: 1.
Each chip is one round: the two heaviest stones and what is left of them.
Input: stones = [2,7,4,1,8,1] Output: 1
Example 2
empty list
Input: stones = [1] Output: 1
Constraints
- 1 <= stones.length <= 30
- 1 <= stones[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
You always need the two heaviest stones, and each smash produces a new stone that must rejoin the pool. A max-heap gives you the two largest and reinserts the difference in log time.
Approach
- Put all stones in a max-heap.
- Pop the two largest; if they differ, push the difference back.
- When one or zero stones remain, that is the answer (or 0).
Dry Run
stones = [2, 7, 4, 1, 8, 1]
Python's heapq is a min-heap, so values go in negated and come back out negated:
negated heap [-8, -7, -4, -1, -2, -1] -- heappop now yields the LARGEST stone
smash 8 and 7 -> 1 goes back in stones 4 2 1 1 1
smash 4 and 2 -> 2 goes back in stones 2 1 1 1
smash 2 and 1 -> 1 goes back in stones 1 1 1
smash 1 and 1 -> both destroyed stones 1
answer 1
The negation is load-bearing twice over. Strip every minus sign from this solution
and it pops the two SMALLEST stones each round and pushes a - b, which is now
negative; the run returns -17. Keep abs on the difference but still pop the
smallest pair and it returns 3. In both cases the algorithm still looks right and
only the number is wrong, which is the hard kind of bug to catch by reading.
The final round smashes two equal stones and pushes nothing. That guard is
tidiness, not correctness: deleting `if a != b` so a zero stone is always pushed
changes no answer on 2000 random inputs, because a zero can never be the larger
of a later pair.Complexity
- Time — O(n log n): each smash is a couple of log-time heap operations.
- Space — O(n): the heap.
Common Pitfalls
- Negate on the way in and out. Python's
heapqis a min-heap, so without negation you repeatedly smash the two smallest stones and push a negative difference, which returns -17 where the answer is 1. - Pushing
a - bwhen the stones are equal is not a bug, which is worth knowing before you go looking: it pushes a zero stone, and a zero can never be the larger of a later pair, so the result is unchanged. The guard is tidiness, not correctness.
Full Solution — all languages
class Solution:
def lastStoneWeight(self, nums):
import heapq
h=[-s for s in nums]
heapq.heapify(h)
while len(h)>1:
a=-heapq.heappop(h); b=-heapq.heappop(h)
if a!=b: heapq.heappush(h,-(a-b))
return -h[0] if h else 0import java.util.*;
class Solution {
public int lastStoneWeight(int[] nums) {
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
for(int s:nums)pq.add(s);
while(pq.size()>1) {
int a=pq.poll(),b=pq.poll();
if(a!=b)pq.add(a-b);
}
return pq.isEmpty()?0:pq.peek();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int lastStoneWeight(vector<int>& nums) {
priority_queue<int> pq(nums.begin(),nums.end());
while(pq.size()>1) {
int a=pq.top();
pq.pop();
int b=pq.top();
pq.pop();
if(a!=b)pq.push(a-b);
}
return pq.empty()?0:pq.top();
}
};/**
* @param {number[]} nums
* @return {number}
*/ var lastStoneWeight = function(nums) {
const h=nums.slice();
while(h.length>1) {
h.sort((x,y)=>x-y);
const b=h.pop(),a=h.pop();
if(a!==b)h.push(b-a);
}
return h.length?h[0]:0;
};