Asteroid collision

Simulate asteroids moving right (positive) or left (negative) along a line, where a collision destroys the smaller one, using a stack of survivors.

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Only a right-mover on the stack followed by a left-mover can collide, since two right-movers never meet and a left-mover followed by anything moving further left never meets either. Compare sizes: the smaller asteroid always explodes, and equal sizes destroy each other, so keep comparing the new asteroid against the stack until it either survives or is gone.

Code

public static int[] AsteroidCollision(int[] asteroids) {
    var stack = new Stack<int>();
    foreach (int a in asteroids) {
        int cur = a;
        while (cur != 0 && cur < 0 && stack.Count > 0 && stack.Peek() > 0) {
            int top = stack.Peek();
            if (Math.Abs(top) < Math.Abs(cur)) stack.Pop();
            else if (Math.Abs(top) == Math.Abs(cur)) { stack.Pop(); cur = 0; }
            else cur = 0;
        }
        if (cur != 0) stack.Push(cur);
    }
    return stack.Reverse().ToArray();
}
static int[] asteroidCollision(int[] asteroids) {
    Deque<Integer> stack = new ArrayDeque<>(); // the last element is the top
    for (int a : asteroids) {
        int cur = a;
        while (cur != 0 && cur < 0 && !stack.isEmpty() && stack.peekLast() > 0) {
            int top = stack.peekLast();
            if (Math.abs(top) < Math.abs(cur)) stack.pollLast();
            else if (Math.abs(top) == Math.abs(cur)) { stack.pollLast(); cur = 0; }
            else cur = 0;
        }
        if (cur != 0) stack.addLast(cur);
    }
    return stack.stream().mapToInt(Integer::intValue).toArray();
}
vector<int> asteroidCollision(const vector<int>& asteroids) {
    vector<int> st; // back() is the top of the stack
    for (int a : asteroids) {
        int cur = a;
        while (cur != 0 && cur < 0 && !st.empty() && st.back() > 0) {
            int top = st.back();
            if (abs(top) < abs(cur)) st.pop_back();
            else if (abs(top) == abs(cur)) { st.pop_back(); cur = 0; }
            else cur = 0;
        }
        if (cur != 0) st.push_back(cur);
    }
    return st;
}
def asteroid_collision(asteroids: list[int]) -> list[int]:
    stack = []
    for a in asteroids:
        cur = a
        while cur != 0 and cur < 0 and stack and stack[-1] > 0:
            top = stack[-1]
            if abs(top) < abs(cur): stack.pop()
            elif abs(top) == abs(cur): stack.pop(); cur = 0
            else: cur = 0
        if cur != 0: stack.append(cur)
    return stack  # bottom to top is left to right

Tips

In the .NET library

stack.Reverse() in C# walks a Stack<T> from top to bottom, so it has to be reversed again to read the survivors in their original left-to-right order.