Last Stone Weight
Difficulty: Easy · Pattern: Heap & Priority Queue · LeetCode #1046
Repeatedly take the two heaviest stones, with weights x ≤ y, and smash them: if x == y both are destroyed; otherwise the result is one stone of weight y − x. When at most one stone remains, return its weight (or 0 if none).
Examples
text
stones = [2, 7, 4, 1, 8, 1] → 1
stones = [10, 10] → 0
stones = [3] → 3Hints
- You always need the current maximum and second maximum. Which data structure provides that quickly?
- Python's
heapqis a min-heap, so push negated weights.
Approach
Put all stones into a max-heap. While at least two remain, pop y (heaviest) and x (second); if they differ, push y − x. Return the remaining stone or 0. Each smash is O(log n), and there are at most n−1 smashes.
Complexity
Time: O(n log n). Space: O(n).
Python solution
import heapq
def lastStoneWeight(stones):
h = [-s for s in stones]
heapq.heapify(h)
while len(h) > 1:
y, x = -heapq.heappop(h), -heapq.heappop(h)
if y != x:
heapq.heappush(h, -(y - x))
return -h[0] if h else 0JavaScript solution
class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
get 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) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
pop() { const a = this.a, top = a[0], last = a.pop();
if (a.length) { a[0] = last; let i = 0;
for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
return top; }
}
function lastStoneWeight(stones) {
const h = new MinHeap((a, b) => b - a); // max-heap via comparator
for (const s of stones) h.push(s);
while (h.size > 1) {
const y = h.pop(), x = h.pop();
if (y !== x) h.push(y - x);
}
return h.size ? h.peek() : 0;
}