Example 1
ready- Input
stones = [ 2, 7, 4, 1, 8, 1 ]- Expected
1- Why
- the collisions eventually leave one stone weighing 1
Imagine a tournament where the two strongest stones collide every round. Equal rivals both disappear; an uneven match sends only their weight difference back into the arena.
You're given the positive weights in stones. Repeatedly choose the two heaviest
remaining stones. Call their weights x and y, where x <= y:
x == y, remove both.y - x.Return the final stone's weight. Return 0 when every stone disappears.
1 <= stones.length <= 30_0001 <= stones[i] <= 1_000Hints
Sort the remaining weights, remove the last two, and put their difference back. That gives you a trustworthy first solution.
You need the two largest values every round, but repeated sorting rebuilds far more order than you use. Which structure keeps its largest value ready?
A max-heap is a structure that exposes its largest stored value first. Pop twice,
push y - x when it's nonzero, and stop when fewer than two weights remain.
Stone weights never exceed 1,000. Could a frequency table replace the heap, and what would its running time depend on?
Visible cases
stones = [
2,
7,
4,
1,
8,
1
]1stones = [
1,
1
]0stones = [
5
]5Interview signal
Keep a working copy of the weights. Sort it, remove the two largest values, and return their difference to the list when that difference is nonzero.
def last_stone_weight(stones: list[int]) -> int:
arena = stones[:]
while len(arena) > 1:
arena.sort()
heavier = arena.pop()
lighter = arena.pop()
if heavier != lighter:
arena.append(heavier - lighter)
return arena[0] if arena else 0The code mirrors the game exactly, which makes it a useful correctness baseline. Its cost is the repeated sorting: almost the same list may be sorted again after every collision.
Time O(n² log n), space O(n) for the working copy.
A max-heap keeps the current largest value at its root. Python's standard heap is a min-heap, so store each weight as a negative number: the most negative entry represents the heaviest stone.
import heapq
def last_stone_weight(stones: list[int]) -> int:
arena = [-weight for weight in stones]
heapq.heapify(arena)
while len(arena) > 1:
heavier = -heapq.heappop(arena)
lighter = -heapq.heappop(arena)
if heavier != lighter:
heapq.heappush(arena, -(heavier - lighter))
return -arena[0] if arena else 0Every round performs two removals and at most one insertion. There are at most n - 1
rounds because each collision reduces the number of stones by at least one.
Time O(n log n), space O(n) for the heap.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
1