← Whiteboard questions

Last Stone Weight

Smash the two heaviest stones (here, melt ingots) until at most one is left.

DSA, Easy, Heap / Priority Queue

Which structure or algorithm, and what does it cost.

A furnace holds ingots with the weights in the list ingots. Each round, take the two heaviest ingots and melt them together. If their weights are equal, both disappear. If not, one ingot stays, and its weight is the difference between the two. Repeat until at most one ingot is left. Return the weight of the last ingot, or 0 if none is left.

Examples

Input ingots = [9, 4, 7, 1]
Output 1
Why 9 and 7 melt into 2. Then 4 and 2 melt into 2. Then 2 and 1 melt into 1.
Input ingots = [5, 5]
Output 0
Why the two equal ingots both disappear, so nothing is left.
Input ingots = [6, 6, 6]
Output 6
Why two of the 6s disappear, and the third is left alone.

Constraints

Your answer must contain

Target Aim for O(n log n) time and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Each round needs the two largest values. Think about what makes finding them again and again slow.

Hint 2 the approach

Sorting once is not enough, because the difference goes back into the pile. You need a structure that always hands you the largest.

Hint 3 the key step

Use a max-heap. Pop two, push back their difference if it is not zero, and stop when fewer than two remain.

Walkthrough

Full walkthrough brute force to best

Brute force

Each round, sort the list, take the two largest and put back the difference. A sort per round costs O(n log n), and there can be almost n rounds, so the total is O(n^2 log n). With 20,000 ingots that is too slow.

Better method

Sort once, then keep the list sorted: pop the two largest from the end and insert the difference with binary search. The search is O(log n), but the insert shifts up to n values, so the total is O(n^2). That is fine at 20,000, but the heap gives O(n log n).

Best method

A max-heap hands over its largest value and accepts a new value, each in O(log n). Pop the two largest ingots. If they differ, push their difference back. Each round removes at least one ingot, so there are fewer than n rounds, and each round does at most three heap steps. When fewer than two ingots remain, the heap holds the answer, or nothing, which means 0. Python's heapq is a min-heap, so store negative weights.

Hand trace

Run on [9, 4, 7, 1]. The heap holds 9, 7, 4, 1. Pop 9 and 7. They differ, so push 2. The heap holds 4, 2, 1. Pop 4 and 2. Push 2. The heap holds 2, 1. Pop 2 and 1. Push 1. One ingot remains, so the answer is 1.

Code

import heapq
def last_ingot(ingots):
    heap = [-w for w in ingots]         # negative weights: heapq is a min-heap
    heapq.heapify(heap)
    while len(heap) > 1:
        a = -heapq.heappop(heap)
        b = -heapq.heappop(heap)
        if a != b:
            heapq.heappush(heap, -(a - b))
    return -heap[0] if heap else 0

Time and memory

O(n log n) time: building the heap is O(n), and fewer than n rounds each do at most three steps of O(log n). O(n) memory for the heap.

Common mistakes

  • Returning the last value you popped without checking whether anything is left. With [5, 5] the answer is 0.
  • Pushing a zero difference is harmless (it is the smallest item, and x - 0 = x), but if you skip zeros you must return 0 when the heap ends empty.
  • Forgetting that heapq is a min-heap. Without negative weights you melt the two lightest ingots.

Related problems

More Heap / Priority Queue problems
Last Stone Weight: hints, walkthrough and Python solution