The problem, in one line. Repeatedly smash the two heaviest stones together, keep the leftover if their weights differ, and report the weight of the last stone, or zero if none is left. LeetCode 1046.
The tell. Each round asks for the biggest thing, then changes the pile and asks again. When “the heaviest, over and over” is the loop, you want a heap.
The wrong first idea
Sort the stones at the start of every round and take the last two.
It is correct. Sorting costs n log n and you do it up to n times, so the whole thing is about n squared log n. The pile barely changes between rounds: two stones leave and at most one returns. A full sort throws away all the order it just built.
The invariant
A heap is a pile that always shows you its biggest stone and fixes itself after each change. Python’s heap shows the smallest, so store each weight negated.
[2,7,4,1,8,1] 8 hits 7 -> 1 left
[2,4,1,1,1] 4 hits 2 -> 2 left
[2,1,1,1] 2 hits 1 -> 1 left, and so on down to one stone: 1
The sentence that stays true every step: the heap holds exactly the stones still alive, and its top is the heaviest. Each round costs two pops and at most one push.
The solution
import heapq
def last_stone_weight(stones):
heap = [-s for s in stones] # heapq is a min-heap, so negate for max
heapq.heapify(heap)
while len(heap) > 1:
a = -heapq.heappop(heap) # heaviest
b = -heapq.heappop(heap) # second heaviest
if a != b:
heapq.heappush(heap, -(a - b))
return -heap[0] if heap else 0
print(last_stone_weight([2, 7, 4, 1, 8, 1]))
print(last_stone_weight([5]))
print(last_stone_weight([3, 3]))
1
5
0
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 any) { *h = append(*h, x.(int)) }
func (h *maxHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func lastStoneWeight(stones []int) int {
h := maxHeap(append([]int{}, stones...))
heap.Init(&h)
for h.Len() > 1 {
a := heap.Pop(&h).(int) // heaviest
b := heap.Pop(&h).(int) // second heaviest
if a != b {
heap.Push(&h, a-b)
}
}
if h.Len() == 0 {
return 0
}
return h[0]
}
Go needs the heap type spelled out, and imports container/heap. Same calls print 1, 5, 0.
Complexity
- Time O(n log n): at most n rounds, each with two pops and one push at log n apiece.
- Space O(n) for the heap.
Traps
- Pushing the weights without negating them. Python then pops the lightest stone, and
[2,7,4,1,8,1]smashes the wrong pair. - Reading the top of an empty heap.
[3,3]destroys both stones, so the final line needs the empty check. - Pushing the difference with the wrong sign,
a - binstead of-(a - b). The leftover then looks like the lightest stone in the pile.
Next in the ladder
Kth Largest Element in a Stream keeps a heap too, but the heap now stays small on purpose, and the question is about a rank rather than the top.