Skip to content

visual walkthrough

Asteroid Collision

MediumStack SimulationReported at: AmazonMetaMicrosoft+4

Collision rules make you think about exactly when to pop.

Solve on LeetCode

The idea

Asteroids only collide when a right-mover is immediately followed by a left-mover. The stack holds the survivors; a new left-mover fights the right-mover on top, destroying smaller ones until it is destroyed itself or reaches safety.

Everything else (a right-mover, or a left-mover with nothing moving right before it) just joins the stack.

Complexity

approachtimespace
Find a collision, repeatO(n²)O(n)
Stack of survivorsO(n)O(n)

More walkthroughs