Asteroid Collision
Master this topic with zero to advance depth.
Asteroid Collision
Calculate the final state of asteroids after all possible collisions. Positive integers move right, negative move left. If two asteroids meet, the smaller one explodes. If they are the same size, both explode.
Visual Representation
asteroids = [5, 10, -5]
1. 5: Push. Stack: [5]
2. 10: Push (same direction). Stack: [5, 10]
3. -5: Moves left. 10 > |-5|. -5 explodes.
Final State: [5, 10]Examples
Level I: Brute Force (Repeated Simulation)
Intuition
Repeatedly scan the list for the first pair of adjacent asteroids that collide (positive followed immediately by negative). Resolve it and restart from the beginning. Repeat until no more collisions exist.
Level III: Optimal (Stack Simulation)
Intuition
Use a stack to track asteroids moving right. When a left-moving asteroid appears, it collides with right-moving ones on the stack top. Continue popping from the stack as long as the right-moving asteroid is smaller. Handle tie-breaks where both explode.
Detailed Dry Run
| Ast | Action | Stack Status | Collision Result |
|---|---|---|---|
| 5 | Push | [5] | - |
| 10 | Push | [5, 10] | - |
| -5 | Compare | [5, 10] | -5 explodes (10 > 5) |
| -12 | Compare | [] | 10 explodes, 5 explodes, -12 stays |
⚠️ Common Pitfalls & Tips
Be careful handle the case where a left-moving asteroid destroys everything in the stack and still survives. Also, ensure tie-cases (same size) are handled correctly.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.