Last Stone Weight II solution explained
Last Stone Weight II asks for the lightest stone that can remain, and the answer is the smallest possible difference between two groups of the stones. Every smash order leaves sum(A) - sum(B) for some split into groups A and B, and the best split is reachable, so the task becomes subset sum: find the largest reachable total no bigger than half of the overall sum, call it best, and return total - 2 * best. A boolean table over sums 0 to total / 2 does it in O(n * total) time.
By Evin JohnPublished 8 min read
The problem in plain words
You have a pile of stones with positive integer weights. At each turn you choose any two of them and smash them together. If they weigh the same, both disappear. If not, the lighter one disappears and the heavier one keeps the difference as its new weight. You continue until at most one stone is left. You choose the pairs freely, and the goal is to make the remaining stone as light as possible, returning its weight, or 0 when nothing is left.
The name points back to an easier problem where you must always smash the two heaviest stones. That version is a heap simulation. Here the order is yours, and the heap rule is no longer optimal, which the page shows below with a five-stone pile.
| Stones | Smallest last stone | A best split |
|---|---|---|
| 4, 4, 3, 3, 3 | 1 | 4 + 4 against 3 + 3 + 3 |
| 12, 7, 3, 1, 1 | 0 | 12 against 7 + 3 + 1 + 1 |
| 9, 2, 2, 1 | 4 | 9 against 5: the big stone cannot be balanced |
| 5, 5, 5 | 5 | 5 + 5 against 5 |
| 1, 1, 1, 1, 40 | 36 | 40 against 4 |
What the interviewer wants to see
Almost nobody is expected to simulate their way to the answer. The question exists to see whether you can find the reformulation. Interviewers listen for the moment you write the final weight as a sum with plus and minus signs, then for the move from 'smallest signed sum' to 'two groups as close as possible', and finally for a correct subset-sum table. Explaining why every best split can actually be played out is a strong extra; a short argument is below.
Brute force: try every smash order
A direct search picks every pair, smashes it, and recurses on the smaller pile, remembering the best result. Caching on the sorted pile helps a little, but the number of distinct piles still grows very fast with the number of stones. It is a useful reference for testing and a reasonable thing to mention for a few seconds before moving on.
@@last-stone-weight-ii/slow.py@@The insight: signs, not order
Follow one original stone through the game. Each time it is smashed it is either added (it was heavier) or subtracted (it was lighter) inside the surviving value. Unwind every smash and the last stone equals a sum of all the original weights, each with a plus or a minus sign. Group the plus stones into A and the minus stones into B, and the last stone weighs sum(A) - sum(B). So no smash order can beat the smallest possible gap between two groups.
The other direction also holds: the smallest gap can always be reached. Take the best split, with A the heavier side and gap D. Smash any stone of A against any stone of B; the survivor stays on the side of the heavier of the two, and the gap between the sides is still D. Keep doing this until one side is empty. Because weights are positive, B empties first or both do, and A then holds total weight D. Any further smashes inside A leave a stone weighing at most D, and nothing can be lighter than the smallest gap, so the result is exactly D.
The pattern: subset sum up to half the total
Write S for the total weight. If the lighter group sums to x, the gap is S - 2x, so you want the largest reachable x that does not exceed S / 2. A boolean array can[s] answers 'can some stones add up to s?'. Start with only can[0] true. For each stone of weight w, sweep s from S / 2 down to w and set can[s] when can[s - w] is true. The downward sweep keeps each stone from being used twice, exactly as in any 0/1 knapsack. At the end, scan down from S / 2 for the first true entry.
@@last-stone-weight-ii/fast.py@@The bitset version is a neat Python trick: bit s of the integer reach is set when sum s is reachable, and reach | (reach << w) adds stone w to every reachable sum at once. Python integers grow as needed, so it handles any total. In JavaScript, a Uint8Array table is the plain choice; a BigInt bitset also works but is slower and harder to read in an interview.
@@last-stone-weight-ii/fast.js@@Why the heaviest-two rule fails
Take stones 3, 3, 2, 2, 2. Smashing the two heaviest each time goes 3 and 3 (both vanish), then 2 and 2 (both vanish), leaving 2. Splitting into 3 + 3 and 2 + 2 + 2 gives two groups of 6, a gap of 0, and the cross-group play-out reaches it: 3 against 2 leaves 1, 3 against 2 leaves 1, 2 against 1 leaves 1, and 1 against 1 leaves nothing. An exhaustive check of every pile of up to five stones with weights from 1 to 12 found no counterexample with four or fewer stones, so this one is about as small as they come. The 4, 4, 3, 3, 3 pile in the table above fails the same way: the rule leaves 3 where 1 is possible.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Simulate every smash order | Exponential in n | Grows with the cache of piles |
| Try every sign assignment | O(2^n * n) | O(n) |
| Boolean subset-sum table | O(n * S) | O(S) |
| Integer bitset (Python) | O(n * S / word size) word operations | O(S) bits |
The table is pseudo-polynomial: fast when the total weight is in the thousands, slow when weights are huge. If an interviewer raises that case, say that with very large weights and few stones a meet-in-the-middle search over the two halves of the list is the usual alternative.
Edge cases
- One stone: nothing to smash, return its weight.
- Two equal stones: they cancel and the answer is 0.
- One stone heavier than all the others combined: the answer is that stone minus the rest, as in 1, 1, 1, 1, 40.
- All stones equal: the answer is 0 for an even count and the stone's weight for an odd count.
- An odd total can never reach 0, so the answer is at least 1.
Mistakes to avoid
- Reusing the heap solution from the first Last Stone Weight problem; the pile 3, 3, 2, 2, 2 breaks it.
- Sweeping s upward, which lets one stone be counted several times.
- Returning S - best instead of S - 2 * best: the gap is the heavier group minus the lighter one.
- Sizing the table to S / 2 but forgetting the + 1, so the half itself is never checked.
- Asserting the reduction without being able to say why every split can be played out.
How to explain it out loud
Fictional example
- Candidate
- If I trace any order of smashes, each original stone ends up added or subtracted in the last one. So the result is the difference between two groups.
- Interviewer
- Can you always reach the best split?
- Candidate
- Yes, if I only smash across the groups the difference stays fixed, and once the lighter side runs out the leftover weighs at most that difference. So I need the lighter group as close to half the total as possible.
- Candidate
- That's subset sum up to S over 2. One boolean array, stones in the outer loop, sums swept downward. Time is n times S.
Related problems
Ones and Zeroes is the same 0/1 table with two capacities instead of one. Stone Game also involves stones, but there two players take turns and the tool is an interval table instead of subset sum. Profitable Schemes counts subsets rather than asking whether one exists. Partition Equal Subset Sum is this exact table with a yes or no question, and Target Sum asks how many sign assignments reach a given value.
Where Natively fits in your practice
Reformulation problems are worth rehearsing out loud, because the insight is the whole answer. When you practice on your computer, Natively can take a screenshot of the prompt, nudge you toward the signed-sum view if you get stuck simulating, and play the interviewer who asks whether the best split is always reachable. The saved transcript lets you check later how long you spent before naming subset sum.
Questions people ask
How do you solve Last Stone Weight II?
Split the stones into two groups whose totals are as close as possible. Use a subset-sum table to find the largest reachable total no bigger than half the overall sum S, call it best, and return S - 2 * best.
Why is Last Stone Weight II a subset sum problem?
Every smash adds one stone and subtracts the other inside the survivor, so the last stone is a signed sum of the original weights: one group minus the other. The closest split can always be played out, so it is the answer.
Does the heap solution from Last Stone Weight work for part II?
No. Smashing the two heaviest stones each time leaves 2 for the pile 3, 3, 2, 2, 2, while splitting it into 3 + 3 and 2 + 2 + 2 leaves nothing.
What is the time complexity of Last Stone Weight II?
O(n * S) time and O(S) memory for n stones with total weight S, using a boolean table over sums from 0 to S / 2.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
