Implement the asteroidCollisionSurvivors method that returns the asteroids that remain after all collisions are resolved.
The input contains an integer array asteroids and its length size. Each value represents one asteroid moving in a line.
A positive value moves to the right, and a negative value moves to the left. When two asteroids moving toward each other meet, the smaller one is destroyed. If both have the same size, both are destroyed.
Your task is to return the asteroids that remain after all possible collisions are resolved.
Use a stack to store asteroids that are still alive.
A collision can happen only when the asteroid on the top of the stack is moving right and the current asteroid is moving left. Compare their absolute sizes. The smaller asteroid is removed. If both sizes are equal, both are removed.
If the current asteroid survives all collisions, push it into the stack. At the end, the stack contains the survivors in their original order.
Pseudocode:
function asteroidCollisionSurvivors(asteroids, size):
stack = empty stack
for each asteroid in asteroids:
alive = true
while alive and asteroid < 0 and stack is not empty and top(stack) > 0:
if top(stack) < absolute(asteroid):
pop stack
else if top(stack) == absolute(asteroid):
pop stack
alive = false
else:
alive = false
if alive:
push asteroid into stack
return stack as array