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.

Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
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:

Contents

As per the problem statement, sign of the number represents its direction, positive sign means, it is going towards right and negative sign means, it is going towards left. If the asteroids going in opposite directions, only then they collide, meaning that current asteroid sign should be positive and the next asteroid sign should be negative. There is one more important thing to remember, if the asteroid sizes are same both will explode otherwise the smaller one will explode.

In this approach, we are going to use a Stack, to store asteroids, and since the asteroids will explode only if the current asteroid has negative sign and the top of the stack is a positive sign asteroid, then we apply following rules on which asteroids will explode.

Implementation steps:
import java.util.Arrays; import java.util.Stack; public class AsteroidCollision { static int[] asteroidCollision(int[] asteroids) { Stack<Integer> stack = new Stack<>(); for(int asteroid: asteroids) { boolean add = true; while(asteroid <0 && !stack.isEmpty() && stack.peek() >0) { if(Math.abs(asteroid) == stack.peek()) { stack.pop();// remove the top, and don't add current since both are explode add = false; break; } else if(Math.abs(asteroid) < stack.peek()) { add = false; // current is smaller, so it wil explode, so don't need to add break; } else { stack.pop(); } } if(add) { stack.push(asteroid); } } int[] remaining = new int[stack.size()]; for(int i=0;i<remaining.length; i++) { remaining[i] = stack.get(i); } return remaining; } public static void main(String[] args) { System.out.println(Arrays.toString(asteroidCollision(new int[]{5,10,-5}))); System.out.println(Arrays.toString(asteroidCollision(new int[]{-8, 8}))); System.out.println(Arrays.toString(asteroidCollision(new int[]{8, -8}))); System.out.println(Arrays.toString(asteroidCollision(new int[]{10,2,-5}))); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of input array asteroids.
Space complexity: O(n).

Above implementations source code can be found at GitHub link for Java code