We are given an array asteroids
of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Constraints:
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
This problem involves simulating asteroid collisions. The key to an efficient solution lies in using a stack to track the remaining asteroids. Asteroids are represented by integers: the absolute value is the size, and the sign indicates the direction (positive for right, negative for left).
Approach:
We iterate through the asteroids
array from left to right. The stack will store the asteroids that haven't been destroyed yet.
Positive Asteroid: If the current asteroid x
is positive (moving right), it's added to the stack. It won't collide with any asteroids already on the stack (as they are also moving right).
Negative Asteroid: If x
is negative (moving left), we need to check for collisions:
x
(meaning the top asteroid will be destroyed).x
survives and is pushed onto the stack.x
, both are destroyed. We pop the top asteroid.x
destroyed: If the loop finishes and the top asteroid is positive and has a larger size than x
, x
is destroyed; we don't add it to the stack.Time Complexity: O(N), where N is the number of asteroids. Each asteroid is pushed and popped at most once. The while loop inside the iteration doesn't affect the overall linear time complexity because, in the worst case, it processes each asteroid in the stack once.
Space Complexity: O(N) in the worst case, as the stack could hold all asteroids.
Code Examples: (Python, Java, C++, Go, TypeScript, Rust)
The provided code examples in various languages all follow the same algorithm. They differ only in syntax and data structure implementations. The core logic remains the same: using a stack to efficiently manage collisions and track surviving asteroids. The while
loop handles the collision resolution effectively, ensuring the correct outcome for each potential collision.