The Asteroid Collision interview question simulates a row of asteroids moving in space. Each asteroid has a size (absolute value) and a direction (positive for right, negative for left). When two asteroids collide, the smaller one explodes. If they are the same size, both explode. Asteroids moving in the same direction or moving away from each other never collide. This Asteroid Collision coding problem is a perfect simulation of stack-based interaction.
This is a high-frequency question at companies like Apple, Google, and Amazon. It tests if a candidate can recognize that only "local" interactions (the rightmost asteroid and the incoming left-moving asteroid) determine the next state. It evaluates your ability to handle complex "while" loop conditions within a traversal.
The Array, Simulation, Stack interview pattern is the standard solution. You use a stack to keep track of asteroids moving to the right. When you encounter an asteroid moving to the left, you compare it with the top of the stack and resolve the collisions until the left-moving asteroid is destroyed or the stack no longer has right-moving asteroids.
Asteroids: [5, 10, -5]
Whenever you have elements that "interact" or "cancel each other out" based on their order, think of a Stack. It allows you to focus on the most recent "active" element and resolve its fate before moving on.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Validate Stack Sequences | Medium | Solve | |
| Build an Array With Stack Operations | Medium | Solve | |
| Baseball Game | Easy | Solve | |
| Number of Students Unable to Eat Lunch | Easy | Solve | |
| Robot Collisions | Hard | Solve |