Asteroid Collision
Find which asteroids are left after the ones flying toward each other collide, with a stack.
An array asteroids
Example 1
Output: [5, 10]
Explanation: 10 and -5 collide and 10 survives.
Example 2
Output: []
Explanation: 8 and -8 are the same size, so both explode.
Example 3
Output: [10]
Explanation: -5 destroys 2, then 10 destroys -5.
The Idea
Picture asteroids floating in space on one straight line, all flying at the same speed. Each number in asteroids10-5
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]
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.
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-a
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
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
- First, create
, anstack used as a stack. ItsArrayDeque adds to the top,push reads the top, andpeek removes the top.pop - Go through the row with a
loop, one asteroidfor at a time, and set the flaga toalive .true - Inside, a
loop runs as long aswhile is alive, moves left (a ), and meets a top that moves right (a < 0 ). Read the top intostack.peek() > 0 . Iftop , pop it and loop again. Otherwise pop it only iftop < -a , and settop == -a toalive .false - After the
loop, pushwhile if it is still alive.a - Finally, create
with the size of the stack, fill it from the last position to the first by popping, and return it.result
The main
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:
[5, 10]
[]
[10]
[-2, -1, 1, 2]
[-10]
[-2, 7]
Look at the third line, [10][-2, -1, 1, 2]
The fifth line, [-10]whileifwhile[3, 4, -10][10, -5]
In the last line, [-2, 7]
The original implementation,
Complexity
The work is one pass over the row, the pops inside the whileresult
- 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
loop together pop at most n times, and the copy intowhile is one more pass of at most n.result - Space: O(n). When nothing meets, as in a row where every asteroid moves right, the stack holds all n asteroids.
is the output and has the size of the final stack.result
A new item that removes items from the top of a stack also drives