735. Asteroid Collision – Leetcode – Java – Explanation

Problem statement

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.

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.

Example 4:

Input: asteroids = [-2,-1,1,2]
Output: [-2,-1,1,2]
Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other.

Constraints:

  • 2 <= asteroids.length <= 104
  • -1000 <= asteroids[i] <= 1000
    Advertisement
  • asteroids[i] != 0

Solution

Intuition is similar to resolving expression like we will be looking for negative asteroids after a positive asteroid, so they can collide and form the resultant. We will keep adding the asteroids if we don’t get this combination. There are multiple ways to solve this problem. We will be discussing two solutions here. a) Using LinkedList 2) Using stack

Using LinkedList

  1. Create a LinkedList object to store asteroids.
  2. Loop asteroids from 0 to N
    • a) If asteroids is positive or list is empty or last element was a negative asteroid
      • Add asteroid to list
    • b) else if asteroid’s size is bigger than the last element, remove it
      • If it’s equal decrement counter, to process that asteroid again.
  3. Add all the remaining elements from list to integer array and return.
class Solution {
    public int[] asteroidCollision(int[] asteroids) {
      	if (asteroids.length == 0 || asteroids.length == 1)
          return asteroids;

        LinkedList<Integer> list = new LinkedList<>();
        
        for (int i = 0; i < asteroids.length; i++) {
            // if asteroids is positive or list is empty or last element was a negative asteroid, add asteroid to list
            if (asteroids[i] > 0 || list.isEmpty() || list.getLast() < 0)
                list.add(asteroids[i]);
            else if (list.getLast() <= -asteroids[i])
                if (list.pollLast() < -asteroids[i]) i--;
        }
        
        int[] ans = new int[list.size()];
        while (!list.isEmpty())
			ans[list.size() - 1] = list.pollLast();
		return ans;
    }
}

Using Stack

  1. Create a stack object to store asteroids.
  2. Loop asteroids from 0 to N
    • a) collision loop: while stack is not empty and asteroid is negative and last value is positive
      • if peek’s size is less than current asteroid then pop last element and continue the loop
      • if peek’s size is eqal to current asteroid then pop the last element and break collision loop
    • push the asteroid to stack
  3. Add all the remaining elements from list to integer array and return.
class Solution {
   
    
    public int[] asteroidCollision(int[] asteroids) {
		if (asteroids.length == 0 || asteroids.length == 1)
			return asteroids;
      
		Stack<Integer> stack = new Stack();
      
        for (int ast: asteroids) {
            collision: {
                while (!stack.isEmpty() && ast < 0 && 0 < stack.peek()) {
                    if (stack.peek() < -ast) {
                        stack.pop();
                        continue;
                    } else if (stack.peek() == -ast) {
                        stack.pop();
                    }
                    break collision;
                }
                stack.push(ast);
            }
        }
		int[] ans = new int[stack.size()];
		while (!stack.isEmpty())
			ans[stack.size() - 1] = stack.pop();
		return ans;
	}
}

For any doubts or corrections please comment on your queries below.

Advertisement

Leave a Reply

Your email address will not be published. Required fields are marked *

4 + 11 =