You have a pile of stones, and stones[i] is the weight of stone i. Each turn, pick up the two heaviest stones and smash them into each other.
If they weigh the same, both break and disappear. If not, the lighter one breaks and the heavier one loses that much weight: a 9 and a 5 leave one stone of 4. Turns go on until at most one stone is left.
Return the weight of that last stone, or 0 if nothing is left.
Example 1
Input: stones = [3, 9, 5, 2] Output: 1 Why: 9 vs 5 leaves 4, 4 vs 3 leaves 1, 2 vs 1 leaves 1
2 more examples and the constraints
Example 2
Input: stones = [6, 6] Output: 0 Why: equal weights, so both break
Example 3
Input: stones = [10] Output: 10 Why: one stone, no turns
Constraints
- 1 ≤ number of stones ≤ 30
- Each stone weighs between 1 and 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort every turnO(n² log n)
- Max-heapO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30 stones | Verdict |
|---|---|---|---|
| Sort every turn | O(n² log n) | Passes; repeats the sort | |
| Max-heap | O(n log n) | Best; the answer they expect |
n = how many stones there are.
Edge cases to test
- One stone. [10] has no turns; return 10.
- Everything breaks. [6, 6] or [2, 2, 2, 2] leave nothing, so return 0.
- A leftover is still the heaviest. [1000, 1] leaves 999; the pushed stone may go straight back on top.
- Odd number of equal stones. [1, 1, 1] leaves a single 1.
Common mistakes
- Using Python’s
heapqas if it were a max-heap, which smashes the lightest stones. - Returning
heap[0]without checking the heap is empty. - Pushing a 0 back when two stones are equal, which leaves a stone that should not exist.
How to talk through it
- 1Clarify. Do equal stones both disappear? What should come back when nothing is left?
- 2Give the simple version. Sort before each turn and take the two at the end; it passes for 30 stones.
- 3Name the waste. Only the top two matter each turn, so keeping the whole list sorted is extra work.
- 4Code the heap. Pop two, push the difference if it is not zero. Mention negating weights in Python.
- 5Test out loud. Run the one-stone and everything-breaks cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?