Intermediate Level

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.

Example 1
Input:
asteroids (int[]) = [5,10,-5]
size (int) = 3
Return:
(int[]) [5,10]
Example 2
Input:
asteroids (int[]) = [8,-8]
size (int) = 2
Return:
(int[]) []
Example 3
Input:
asteroids (int[]) = [10,2,-5]
size (int) = 3
Return:
(int[]) [10]

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
Run your code to see the result.