Python coding

Last stone left after smashing

You have a pile of stones whose weights, positive integers, are in stones. Each turn, take the two heaviest stones, weighing x ≤ y, and smash them together: if x == y both are destroyed, otherwise the lighter one is destroyed and the other now weighs y - x. Repeat while at least two stones remain. Return the weight of the stone left at the end, or 0 if none is left.

Aim for O(n log n): don't re-sort the pile on every turn.

Besides the tests, one large input (20,000 stones) with a ~450 ms limit (scaled to your device's speed): brute force won't pass.

  • last_stone([2,7,4,1,8,1]) → 1
  • last_stone([3,3]) → 0
  • last_stone([10,4]) → 6
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every turn needs the two heaviest stones of a pile that keeps changing. A heap hands you the heaviest in O(log n); sorting the pile again every turn costs far more.

Hint 2

heapq is a min-heap, so store the weights negated. Pop twice; if the two weights differ, push the negated difference back.

Solution and why it works
pythonO(n log n) · O(n)
import heapq


def last_stone(stones: list[int]) -> int:
    heap = [-s for s in stones]              # max-heap: the weights are negated
    heapq.heapify(heap)
    while len(heap) > 1:
        y = -heapq.heappop(heap)             # the heaviest
        x = -heapq.heappop(heap)             # the second heaviest
        if y > x:
            heapq.heappush(heap, x - y)      # what is left, y - x, negated
    return -heap[0] if heap else 0

A max-heap keeps the heaviest stone at its root while the pile changes, so each turn is two pops and at most one push, O(log n). Every smash removes at least one stone, so there are fewer than n turns. heapq is a min-heap, hence the negated weights. Traps: forgetting the negation, which smashes the two lightest stones instead, and re-sorting the whole pile every turn, which makes the work quadratic.