Problem Description
Given an array of integers where each integer represents an asteroid (its absolute value for size and sign for direction: positive for right-moving and negative for left-moving), simulate all collisions between asteroids. When two asteroids meet, the smaller one explodes; if they are equal in size, both explode. Asteroids moving in the same direction never collide. Return the final state of the asteroids after all possible collisions.
Key Insights
- Use a stack to keep track of the surviving asteroids.
- Only a collision happens when a right-moving asteroid (positive) is on the stack and a left-moving asteroid (negative) is encountered.
- Compare the absolute values to decide if one or both asteroids explode.
- Continue processing collisions until no further collisions are possible with the current asteroid.
Space and Time Complexity
Time Complexity: O(n) where n is the number of asteroids, since each asteroid is pushed and popped at most once. Space Complexity: O(n) in the worst case, when no collisions occur and all asteroids remain on the stack.
Solution
The solution uses a stack to simulate the asteroid collision process. For each asteroid in the input:
- If it is moving to the right or the stack is empty, simply add it to the stack.
- If it is moving to the left, check the asteroid on top of the stack:
- If the top asteroid is moving to the right, they might collide.
- Compare sizes:
- If the left-moving asteroid is larger (in absolute terms), pop the stack and continue checking.
- If both are equal, pop the stack and do not add the current asteroid.
- If the right-moving asteroid is larger, the current asteroid explodes.
- If no collision occurs for the current asteroid, push it onto the stack. Finally, the stack represents the surviving asteroids order.