progress

~/problems / Heaps / Heaps and priority queues

Last Stone Weight

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A quarry crusher repeatedly smashes the two heaviest rocks in the pile together. Equal rocks both turn to dust; otherwise the lighter one is destroyed and the heavier one, now a - b, goes back on the pile.

Write last_rock(weights) -> int: the weight of the last rock left, or 0 if none is.

last_rock([3, 8, 2, 6, 1])   # 0   (8,6 -> 2; 3,2 -> 1; 2,1 -> 1; 1,1 -> dust)
last_rock([10, 4])           # 6
last_rock([9])               # 9
last_rock([5, 5, 5])         # 5

Up to 2 * 10^5 rocks, each weighing 1 to 10^9.

⭐ Bonus: speed tests with 200,000 rocks earn a star in O(n log n). Re-sorting the pile before every smash is O(n² log n).

Show hint

Use a structure that hands you the current maximum in O(log n) and takes the leftover back just as cheaply.

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc