Problem

We are given an array asteroids of integers representing asteroids in a row.

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.

Examples

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.

Solution

Method 1 - Using Stack

We can use a stack to simulate the process of collisions:

  1. Iterate through each asteroid.
  2. When an asteroid moves right (positive), simply push it onto the stack.
  3. When an asteroid moves left (negative):
    • Pop asteroids from the stack if they are smaller and moving right.
    • If a collision occurs and both asteroids are of equal size, both explode.
  4. Add surviving asteroids back to the stack.

Code

Java
public class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();

        for (int num : asteroids) {
            if (num > 0) {
                stack.push(num);
            } else {
                while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < Math.abs(num)) {
                    stack.pop(); // collisions of all smaller positive asteroids going towards right
                }

                // stack is empty or asteroid going towards left
                if (stack.isEmpty() || stack.peek() < 0) {
                    stack.push(num);
                } else if (stack.peek() == Math.abs(num)) {
                    stack.pop(); // both asteroids are equal and will explode
                }
            }
        }

        int[] result = new int[stack.size()];
        for (int i = stack.size() - 1; i >= 0; i--) {
            result[i] = stack.pop();
        }
        return result;
    }
}
Python
class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        stack: List[int] = []

        for num in asteroids:
            if num > 0:
                stack.append(num)
            else:
                while stack and stack[-1] > 0 and stack[-1] < abs(num):
                    stack.pop()  # collisions of all smaller positive asteroids going towards right

                # stack is empty or asteroid going towards left
                if not stack or stack[-1] < 0:
                    stack.append(num)
                elif stack[-1] == abs(num):
                    stack.pop()  # both asteroids are equal and will explode
        
        return stack

Complexity

  • ⏰ Time complexity: O(n) where n is the number of asteroids.
  • 🧺 Space complexity: O(n) for the stack used to keep track of remaining asteroids.