mediumStackStack

Asteroid Collision

mediumTime: O(n)Space: O(n)

Recognize the pattern

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

Brute force idea

If you approach Asteroid Collision in the most literal way possible, you get this: 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.

Better approach

A calmer way to see Asteroid Collision is this: 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.

Key invariant

The truth you want to protect throughout Asteroid Collision is this: 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.

Watch out for

A common way to get lost in Asteroid Collision is this: 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