Asteroid Collision Visualization & Animation

Simulates asteroid collisions where larger survive, using a stack to process each asteroid in O(n).

## What is it? Asteroids moving in a row collide when one moves right (+) and another moves left (−). Simulate the collisions — larger asteroids survive and smaller ones explode. Equal-sized asteroids both explode. ## How it works - Use a stack representing surviving asteroids - For each asteroid: - If it moves right (+) → push it (no collision yet) - If it moves left (−): - While stack is not empty and the top is moving right (+) and is smaller than the current → pop (collision, top explodes) - If stack top is equal in magnitude → pop and discard current (both explode) - If stack top is larger → current is destroyed (discard) - If stack is empty or top is also negative → push current ## When to use - Simulation problems with "dominance" or collision mechanics - Stack-based state machine problems ## Key Points - O(n) time — each asteroid pushed and popped at most once - O(n) space for the stack - Careful handling of equal-magnitude collisions (both explode)

Category: algorithms

Difficulty: intermediate

Time Complexity: O(n)

Space Complexity: O(n)

Asteroid Collision

intermediate

Simulates asteroid collisions where larger survive, using a stack to process each asteroid in O(n).

Compares0
Init
empty
Monotonic Stack
i
5
[0]
10
[1]
5
[2]
10
[3]
8
[4]
8
[5]
Survived?
?
[0]
?
[1]
?
[2]
?
[3]
?
[4]
?
[5]
Initialize: empty stack, all asteroids pending.