StackMedium

Asteroid Collision Visualizer

What is Asteroid Collision

Asteroids move in a line. A positive value moves right, a negative value moves left. Two asteroids collide only when a right-mover is already on the stack and a left-mover arrives.

Approach

The stack holds asteroids that are still alive, left to right. Only a negative asteroid can collide with a positive top.

Visualization & algorithm

Alive asteroids after each arrival
for each asteroid x:
while top moves right and x moves left:
if top is smaller: pop it
else if equal: pop top, x dies
else: x dies
if x is still alive: push x
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each asteroid is pushed and popped at most once.
SpaceO(n)No collisions means every asteroid stays.

Implementation

def solve(self, nums):
    st = []
    for x in nums:
        alive = True
        while alive and st and st[-1] > 0 and x < 0:
            if st[-1] < -x: st.pop()
            elif st[-1] == -x:
                st.pop(); alive = False
            else:
                alive = False
        if alive: st.append(x)
    return st