Problem Statement

Asteroid Collision

You are given an array called asteroids. Each number is one asteroid in a row. The size of the asteroid is how big the number is (ignore the sign), and the sign tells you which way it moves: a positive number moves right, and a negative number moves left. Every asteroid moves at the same speed. When two asteroids crash into each other, the smaller one explodes. If they are the same size, both explode. Two asteroids moving the same way never crash, because they stay the same distance apart. Your job is to return what the row looks like after all the crashes are done.

mediumStackStackTime: O(n) · Space: O(n)

Signals to notice

asteroids moving in a linecollisions between opposite directionslast-in determines outcome

Brute force first

Simulate collisions step by step. Each collision removes an asteroid and restarts. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Stack: process left to right. Positive asteroids are pushed. When a negative asteroid arrives, compare with stack top. The larger survives; equal means both destroyed. — each asteroid is pushed and popped at most once. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on asteroids=[10, 2, -5]

a=10 (positive): while-loop skipped, alive=true -> push. stack=[10]
a=2 (positive): while-loop skipped, alive=true -> push. stack=[10, 2]
a=-5 (negative): top=2>0 and 2<abs(-5)=5 -> pop 2. stack=[10]
a=-5 continues: top=10>0, 10<5? no, 10==5? no -> else: alive=false, stop popping. stack=[10]
a=-5: alive=false -> not pushed. stack=[10]
loop ends -> return stack = [10]

What must stay true

Only right-moving (positive) followed by left-moving (negative) causes collisions. The stack holds surviving right-movers. A left-mover collides with the stack top until it's destroyed, destroys the top, or the stack is empty. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

stack = []
for a in asteroids:
    alive = true
    while alive and stack and a < 0 and stack.top > 0:
        if stack.top < |a|:        stack.pop()        # top destroyed, keep checking
        elif stack.top == |a|:     stack.pop(); alive = false   # both destroyed
        else:                      alive = false                # a destroyed
    if alive: stack.push(a)
return stack

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not handling the case where the negative asteroid destroys multiple right-movers — keep popping while the negative is larger than the stack top. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Stack Pattern