Asteroid Collision solution explained
Asteroid Collision gives you a row of rocks as signed integers, where the size is the absolute value and the sign is the direction, and asks which rocks are left once every collision has played out. Keep the survivors on a stack: a right-moving rock is simply pushed, and a left-moving rock fights the right-movers on top of the stack until it breaks, ties, or finds nothing left to hit. Each rock is pushed and popped at most once, so the whole run is O(n).
By Evin JohnPublished 9 min read
The problem in plain words
Picture rocks floating along a straight line. You get them as a list of nonzero integers in left-to-right order. The absolute value is the rock's size. A positive number drifts to the right, a negative number drifts to the left, and every rock moves at the same speed. When two rocks meet, the smaller one shatters and the larger one carries on unchanged. If they are the same size, both shatter. Return the rocks that are still around after nothing else can collide, in their original order.
[4, 7, -5] -> [4, 7] the 7 crushes the -5
[3, 9, -10, 4] -> [-10, 4] the -10 crushes the 9, then the 3
[2, 4, -4, -2] -> [] 4 and -4 tie, then 2 and -2 tie
[-3, -1, 2, 5] -> [-3, -1, 2, 5] nothing ever meetsThe last row surprises people. The two left-movers are already on the left side heading left, and the two right-movers are on the right side heading right. They are moving apart, so no collision happens even though the signs differ. The only arrangement that produces a crash is a positive number somewhere before a negative number.
Good questions before coding: can a value be zero (usually not, so every rock has a direction), does the speed ever differ (no, which is what makes the stack work), and should the output keep the original order (yes).
What the interviewer is looking for
This is a stack question in disguise. There are no brackets and nothing is called a stack, so the test is whether you notice the shape yourself: each new item interacts only with the most recent survivors, and it may wipe out several of them in a row. Interviewers also watch how you handle the three outcomes of a single fight without tangling the loop, and whether you can explain why a left-mover at the front of the row is safe forever.
Brute force: resolve one crash at a time
A direct simulation looks for any adjacent pair where a positive number sits immediately before a negative one, resolves that single crash, and starts scanning again. When a full scan finds no such pair, the row is stable. Every crash removes at least one rock, so there are at most n crashes, and each scan costs O(n). That gives O(n²) in the worst case, for example a long run of small right-movers followed by one huge left-mover. It is still worth writing, because it makes a good reference to test the fast version against.
def collide_slowly(rocks):
row = list(rocks)
settled = False
while not settled:
settled = True
for i in range(len(row) - 1):
a, b = row[i], row[i + 1]
if a > 0 and b < 0:
if a > -b:
del row[i + 1]
elif a < -b:
del row[i]
else:
del row[i:i + 2]
settled = False
break
return rowDoes the order of crashes matter? No. A crash only involves two neighbors, and resolving one pair never changes which rock would win a different pair, so any order reaches the same final row. That is also why the left-to-right stack below gives the right answer.
The stack solution
Walk the row from left to right and keep a stack of rocks that have survived so far. The stack always ends up as some left-movers at the bottom followed by right-movers on top, because any left-mover that reached the stack had nothing left to hit. When the next rock is a right-mover, push it: it cannot hit anything behind it. When it is a left-mover, compare it with the top of the stack while that top is a right-mover. If the top is smaller, pop it and keep going, since the incoming rock is still alive. If the top is the same size, pop it and drop the incoming rock too. If the top is bigger, drop the incoming rock and stop. If the loop ends with the incoming rock still alive, push it.
def asteroid_collision(rocks):
stack = []
for rock in rocks:
alive = True
while alive and rock < 0 and stack and stack[-1] > 0:
top = stack[-1]
if top < -rock:
stack.pop() # the right-mover breaks; keep fighting
elif top == -rock:
stack.pop() # same size: both break
alive = False
else:
alive = False # the incoming rock breaks
if alive:
stack.append(rock)
return stackThe loop condition carries the whole idea. A positive incoming rock skips the loop. A negative rock facing an empty stack, or a stack whose top is also negative, skips the loop too, because those rocks are moving the same way or away from it. Only the case where something heads right and the newcomer heads left enters the loop.
function asteroidCollision(rocks) {
const out = rocks.slice(); // work on a copy; out[0..size) is the stack
let size = 0;
for (const rock of rocks) {
let alive = true;
while (alive && rock < 0 && size > 0 && out[size - 1] > 0) {
const top = out[size - 1];
if (top < -rock) {
size--;
} else {
if (top === -rock) size--;
alive = false;
}
}
if (alive) out[size++] = rock;
}
out.length = size;
return out;
}The JavaScript version treats the front of a copied array as the stack and tracks its size with an index. The write position never passes the read position, so it would also work in place if the caller allows the input to be overwritten. That is a nice follow-up answer when an interviewer asks about memory: the extra space drops to O(1) beyond the output.
Cost of each approach
| Approach | Time | Extra space |
|---|---|---|
| Rescan after every crash | O(n²) worst case | O(n) for the working copy |
| Stack of survivors | O(n): each rock pushed and popped at most once | O(n) for the stack |
| Stack kept in the front of the array | O(n) | O(1) beyond the array itself |
The nested while loop makes the stack version look quadratic at first glance. Count operations per rock instead: every rock is pushed at most once and popped at most once, so the total work across the whole pass is at most 2n stack operations.
Edge cases to test
- An empty row, or a row with a single rock: returned as is.
- Every rock moving the same direction: nothing collides.
- Left-movers first, then right-movers: they move apart, nothing collides.
- A chain of ties, such as [2, 4, -4, -2]: everything disappears.
- One huge left-mover at the end that clears every right-mover before it and then survives.
- A tie right after a sequence of pops, such as [1, 3, -3]: the 1 stays, the 3 and -3 both go.
Mistakes that cost points
- Pushing the incoming rock after a tie. Both rocks are gone, so the flag (or a break with an else clause) must stop the push.
- Treating any sign change as a collision. A negative followed by a positive means the two are drifting apart.
- Comparing raw values instead of sizes, for example checking top < rock rather than top < -rock.
- Stopping after one fight. A big left-mover can destroy many right-movers in a row, so the comparison has to loop.
- Mutating the input in place without saying so, when the caller still needs the original row.
Follow-up questions
- Return how many rocks survive instead of the rocks themselves: the stack size at the end.
- Record every collision as a pair of positions: push indexes instead of values and log each pop.
- Rocks move at different speeds: the stack argument breaks, because a fast rock can overtake and hit something that a slower rock in front never reaches. This becomes an event simulation, and saying so clearly is a good answer.
- The larger rock shrinks by the size of the smaller one instead of staying intact: in each fight, reduce the survivor by the loser's size. If the stack top survives, rewrite its value; if the incoming rock survives, shrink it and keep fighting. Not run here, so trace it by hand before relying on it.
How to explain it out loud
Fictional example
- Candidate
- A crash can only happen when something moving right sits before something moving left. Rocks at the front heading left are gone for good, and rocks at the back heading right never get hit.
- Candidate
- So I will scan left to right and keep the survivors on a stack. Right-movers just get pushed.
- Candidate
- A left-mover fights whatever right-mover is on top. If it wins, I pop and it fights the next one. If they tie, both go. If it loses, it goes and I stop.
- Interviewer
- Isn't that a loop inside a loop?
- Candidate
- It is, but each rock is popped at most once over the whole run, so the total is linear.
Related problems
Asteroid Collision is the friendliest of a family of stack problems where a new item clears older ones off the top. Next Greater Element uses the same pop-while-smaller loop to answer a lookup question, Online Stock Span applies it to a stream of prices, and Remove K Digits uses it greedily to build the smallest number. For the classic introduction to stacks, see Valid Parentheses. For a different pattern entirely, Longest Palindrome is solved by counting.
Practicing this one with Natively
The tie case is where most attempts at this problem go wrong, and it is easy to skip when you rehearse silently. In a practice session, Natively on Mac or Windows can read the row of rocks from a screenshot, point you toward the stack of survivors, and keep a transcript of how you explained the three outcomes so you can see whether you mentioned the tie. Details are on the LeetCode practice helper page.
Questions people ask
How do you solve Asteroid Collision?
Scan the rocks left to right with a stack of survivors. Push right-movers. For a left-mover, pop smaller right-movers off the top, pop and discard both on a tie, and discard the newcomer if the top is bigger. Push it only if it survives.
Why is the Asteroid Collision stack solution O(n) with a nested loop?
Every rock is pushed at most once and popped at most once over the whole run, so the inner loop does at most n pops in total, not n per rock.
Do a negative rock followed by a positive rock collide?
No. The negative one moves left and the positive one moves right, so they drift apart. Only a positive value before a negative value can meet.
What happens when two asteroids are the same size?
Both are destroyed. In code, pop the top and make sure the incoming rock is not pushed afterwards.
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.
