KatInterview

Last Stone Standing: Repeated Smash of the Two Heaviest Weights

Heaps, Sorting & SearchAuto-graded · 28 test cases
EasyAuto-gradedHeaps, Sorting & Searchheappriority-queuesimulation

Last updated

Simulate repeatedly removing the two largest values and reinserting their difference, using a max-heap to find the last remaining value or 0.

Last Stone Standing

You are given a list of positive integers weights. Each integer is the weight of one stone in a pile. You will repeatedly smash stones together until the pile is nearly empty.

One round works like this:

  1. Choose the two heaviest stones currently in the pile. Call their weights a and b, with a <= b. If several stones share a weight, any of them may be used, since equal weights are interchangeable.
  2. Smash them together:
    • If a == b, both stones are destroyed.
    • If a < b, the lighter stone is destroyed and the heavier stone is replaced by a stone of weight b - a, which goes back into the pile.

Keep playing rounds while the pile holds two or more stones.

Task: Return the weight of the last remaining stone. If no stones remain, return 0.

Function

Implement last_stone_weight(weights), which takes the list weights and returns a single integer.

Constraints

  • 1 <= len(weights) <= 10^5
  • 1 <= weights[i] <= 10^9
  • A stone of weight 0 is never placed back in the pile; equal stones simply vanish.
  • A pile with a single stone returns that stone's weight.
  • Your function should not depend on the input list being sorted.

Examples

Example 1

Input: last_stone_weight([2, 7, 4, 1, 8, 1])

Output: 1

Example 2

Input: last_stone_weight([5, 5])

Output: 0

Example 3

Input: last_stone_weight([1])

Output: 1

Example 4

Input: last_stone_weight([3, 7, 3, 7, 9])

Output: 1

Hints

Hint 1

After each smash, the new stone can land anywhere in the ordering, so sorting once at the start is not enough. You need a structure that repeatedly gives you the current maximum and accepts new insertions.

Hint 2

Python's heapq is a min-heap. Store negated weights so that the smallest stored value corresponds to the heaviest stone.

Hint 3

Loop while the heap has at least two items: pop twice, and push the difference only if it is nonzero. At the end, return the single remaining weight, or 0 if the heap is empty.