Asteroid Collision

Find which asteroids are left after the ones flying toward each other collide, with a stack.

An array asteroids describes asteroids in a row, from left to right. An asteroid's size is its number without the sign, and the sign is its direction: positive moves right, negative moves left. All asteroids move at the same speed. When two meet, the smaller one explodes, and if they are the same size, both explode. Two asteroids moving the same way never meet. Return the asteroids that are left after all collisions, in their order.

Example 1
Input: asteroids = [5, 10, -5]
Output: [5, 10]
Explanation: 10 and -5 collide and 10 survives.
Example 2
Input: asteroids = [8, -8]
Output: []
Explanation: 8 and -8 are the same size, so both explode.
Example 3
Input: asteroids = [10, 2, -5]
Output: [10]
Explanation: -5 destroys 2, then 10 destroys -5.
Solution

The Idea

Picture asteroids floating in space on one straight line, all flying at the same speed. Each number in asteroids is one of them. The number 10 is an asteroid of size 10 flying right, and -5 is one of size 5 flying left.

Which asteroids can ever meet? Two flying the same way keep the same gap forever. One flying left that sits to the left of one flying right moves away from it. So two asteroids meet only when a right-mover, one flying right, has a left-mover, one flying left, somewhere to its right.

Follow Example 3, [10, 2, -5]. The asteroids 10 and 2 fly right, and -5 flies left, toward them. It reaches 2 first, because 2 is nearer. 2 is smaller, so 2 explodes. Then -5 flies on and meets 10, which is bigger, so -5 explodes. Only 10 is left.

That raises the question the whole problem turns on: when a left-mover comes in, which asteroid does it hit first? Always the nearest one to its left that is still flying, if that one is a right-mover. If it explodes, the one before it becomes the nearest. So the asteroids still flying get used newest first.

A pile with that rule is called a stack: you add to the top and take from the top, like a pile of plates. Read the asteroids from left to right and keep the ones still flying on a stack. Look at the picture below, which follows Example 3.

The row of asteroids 10, 2 and -5: 10 and 2 move right, -5 moves left. The stack after 10 holds 10, and after 2 it holds 10 with 2 on top. Then -5 arrives: 2 is smaller and explodes, 10 is bigger so -5 explodes, and the stack holds 10.

In the panel labelled "stack after 10", 10 is pushed, which means put on the top. In "stack after 2", 2 is pushed on top of it. In "stack after -5", -5 meets the top, 2. Since 2 < 5, 2 explodes and is taken off. Now 10 is on top, and 10 > 5, so -5 explodes and is never added. The stack holds 10, the answer.

So each new left-mover only ever fights the top of the stack, again and again, until it explodes or nothing in front of it flies right.

Solution Approach

Turning that idea into code means settling three things: what to do with each new asteroid, how a collision with the top ends, and how to read the survivors back in order. Replaying the collisions one at a time also works, and it shows what the stack saves.

Replaying the collisions one at a time

Why not act out the collisions directly? Scan the row for a right-mover followed straight away by a left-mover, remove the one that explodes, or both, and scan again from the start. Each scan reads up to n asteroids, where n is the length of the row.

Each collision removes at least one asteroid, so there can be close to n scans. A row of many small right-movers followed by one big left-mover needs one scan per small right-mover, about n²/2 steps in all. The stack avoids the rescanning: each asteroid goes on it once and comes off at most once.

Handling each new asteroid

What should happen when the next asteroid comes in? If it moves right, nothing to its left can reach it, so it goes on the stack. If it moves left and the stack is empty, or the top also moves left, it will never meet anything either. Everything to its left either flies away from it or flies left at the same speed, so it goes on the stack too.

Only one case is a collision: the new asteroid moves left and the top of the stack moves right.

How a collision ends

Who wins? The new asteroid's number, call it a, is negative, so its size is -a. Compare that with the top. If the top is smaller, it explodes and comes off the stack, and the new asteroid flies on to the next top. That repeats, so it is a loop, not a single check.

If the two are the same size, the top comes off and the new asteroid explodes too. If the top is bigger, only the new asteroid explodes, and the stack stays as it was. A flag named alive records whether the new asteroid is still flying, and it goes on the stack only if it is.

Reading the survivors in order

Once every asteroid has been handled, the stack holds the survivors. Taking them off gives the newest first, the reverse of their order in the row. So the result array is filled from its last position back to its first.

Java Solution

The method asteroidCollision works in these steps:

  1. First, create stack, an ArrayDeque used as a stack. Its push adds to the top, peek reads the top, and pop removes the top.
  2. Go through the row with a for loop, one asteroid a at a time, and set the flag alive to true.
  3. Inside, a while loop runs as long as a is alive, moves left (a < 0), and meets a top that moves right (stack.peek() > 0). Read the top into top. If top < -a, pop it and loop again. Otherwise pop it only if top == -a, and set alive to false.
  4. After the while loop, push a if it is still alive.
  5. Finally, create result with the size of the stack, fill it from the last position to the first by popping, and return it.

The main method runs the three examples, a row where nothing meets, one left-mover that destroys three right-movers in turn, and an equal pair that cancels before two more asteroids arrive.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class AsteroidCollision {

    public static int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> stack = new ArrayDeque<>();   // survivors so far, newest on top
        for (int a : asteroids) {
            boolean alive = true;
            // only a right-mover on the stack and a left-mover arriving can collide
            while (alive && a < 0 && !stack.isEmpty() && stack.peek() > 0) {
                int top = stack.peek();
                if (top < -a) {
                    stack.pop();                     // the top explodes; keep checking
                } else {
                    if (top == -a) {
                        stack.pop();                 // same size: both explode
                    }
                    alive = false;                   // the new asteroid is gone
                }
            }
            if (alive) {
                stack.push(a);
            }
        }
        int[] result = new int[stack.size()];
        for (int i = result.length - 1; i >= 0; i--) {
            result[i] = stack.pop();                 // newest first, so fill from the end
        }
        return result;
    }

    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[] {10, 2, -5})));
        System.out.println(Arrays.toString(asteroidCollision(new int[] {-2, -1, 1, 2})));
        System.out.println(Arrays.toString(asteroidCollision(new int[] {3, 4, 6, -10})));
        System.out.println(Arrays.toString(asteroidCollision(new int[] {1, -1, -2, 7})));
    }
}

Running it prints:

Output
[5, 10]
[]
[10]
[-2, -1, 1, 2]
[-10]
[-2, 7]

Look at the third line, [10]: that is Example 3, the run shown in the picture. The fourth line, [-2, -1, 1, 2], keeps all four, because the two left-movers start on the left and fly away from the right-movers.

The fifth line, [-10], is where the while loop matters. -10 pops 6, then 4, then 3, and finds the stack empty, so it is pushed. A version with if in place of while fights the top only once. It returns [3, 4, -10] for this input and [10, -5] for Example 3.

In the last line, [-2, 7], 1 and -1 are the same size and both explode. That leaves the stack empty, so -2 is pushed, and 7 moves right, away from it.

The original implementation, AsteroidCollision.java, is on GitHub.

Complexity

The work is one pass over the row, the pops inside the while loop, and the copy into result.

  • Time: O(n). One left-mover can pop many asteroids, but each asteroid is pushed at most once and popped at most once. So all runs of the while loop together pop at most n times, and the copy into result is one more pass of at most n.
  • Space: O(n). When nothing meets, as in a row where every asteroid moves right, the stack holds all n asteroids. result is the output and has the size of the final stack.

A new item that removes items from the top of a stack also drives Removing Stars From a String.