Stack-based simulation of all collisions.
function asteroidCollision(asteroids):
stack = []
for ast in asteroids:
alive = true
while alive and ast < 0 and stack is not empty and stack.top() > 0:
if stack.top() < abs(ast):
stack.pop()
else if stack.top() == abs(ast):
stack.pop()
alive = false
else:
alive = false
if alive:
stack.push(ast)
return stack
The alive flag tracks whether the current left-moving asteroid survives its collisions. The while loop handles the case where one large left-moving asteroid destroys multiple smaller right-moving ones in sequence.