You are given an array asteroids; each value is a moving asteroid. Its magnitude is its size and its sign is its direction: positive moves right, negative moves left. All move at the same speed.
Two asteroids collide only when a right-moving one is immediately followed by a left-moving one. The smaller explodes; if they're the same size, both explode. Same-direction asteroids never collide. Return the state of the asteroids after all collisions.
Input: asteroids = [5,10,-5] Output: [5,10] 10 and -5 collide; 10 survives. 5 and 10 move the same way and never collide.
Input: asteroids = [8,-8] Output: [] 8 and -8 are equal size, so both explode.
- 2 <= asteroids.length <= 10^4 - -1000 <= asteroids[i] <= 1000 - asteroids[i] != 0
Only a right-moving asteroid followed by a left-moving one collides — which is exactly a stack situation: the right-movers pile up, and each incoming left-mover fights its way down the stack until it survives, explodes, or annihilates a match. One pass with a stack resolves every collision.
“When do two asteroids collide?”
Only when a right-mover (positive) is immediately to the left of a left-mover (negative).
“What happens on equal sizes?”
Both explode.
A collision only happens when a right-mover meets a left-mover, so I keep a stack of survivors.
An incoming left-mover collides with positive asteroids on top of the stack, one at a time.
It pops smaller ones, annihilates an equal one, or itself explodes against a larger one.
Worked example — asteroids = [10, 2, -5]
10 -> push stack [10]
2 -> push stack [10, 2]
-5 -> collide with 2: |2| < 5, 2 explodes -> stack [10]
collide with 10: |10| > 5, -5 explodes
result: [10]
A collision requires a positive asteroid immediately followed by a negative one. Same-direction or left-then-right pairs never collide — so a left-mover only ever fights the positive asteroids on the stack.
An incoming negative asteroid can destroy several stacked positives in a row, continuing until it's blocked, annihilated, or destroyed.
Each asteroid enters the stack once and is removed at most once, so the whole simulation is O(n).
Key takeaway
Keep a stack of survivors. Push right-movers freely; a left-mover collides with the positive asteroids on top — popping smaller ones, annihilating an equal one, or being destroyed by a larger one. Push it only if it survives. O(n) time.
for a in asteroids:
alive = true
while alive and a < 0 and stack and stack.top > 0:
if stack.top < -a: pop # top explodes, keep colliding
elif stack.top == -a: pop; alive=false # both explode
else: alive = false # a explodes
if alive: push a
return stack