SDE & MLE Prep

735. Asteroid Collision

Problem

Asteroids move along a line: |value| is the size, the sign is the direction (positive right, negative left), all at the same speed. When two collide the smaller one explodes; equal sizes both explode. Asteroids moving the same way never meet. Return the state after all collisions.

Example: [5,10,-5] → [5,10]; [8,-8] → []; [10,2,-5] → [10]

Only a right-mover (stack top > 0) followed by a left-mover (x < 0) collide. While that happens, the smaller explodes; equal sizes both explode.

Complexity: O(n).

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        st = []
        for x in asteroids:
            alive = True
            while alive and x < 0 and st and st[-1] > 0:
                if st[-1] < -x:
                    st.pop()
                    continue
                if st[-1] == -x:
                    st.pop()
                alive = False
            if alive:
                st.append(x)
        return st