Asteroid Collision
Medium
Topics
Given nums of asteroids (absolute value = size, sign = direction: positive right, negative left), return the state after all collisions. Two moving toward each other: the smaller explodes; equal sizes both explode. Same direction never collide.
Example 1
Input: asteroids = [5,10,-5] Output: [5,10]
Example 2
Input: asteroids = [8,-8] Output: []
Example 3
Input: asteroids = [10,2,-5] Output: [10]
Constraints
- 2 <= nums.length <= 10^4
- -1000 <= nums[i] <= 1000
- nums[i] != 0
Editorial — intuition, approach, complexity and pitfalls
Intuition
Asteroids move right (positive) or left (negative). A collision happens only when a right-mover is immediately followed by a left-mover — two moving the same way never meet, and a left-mover followed by a right-mover diverge.
That "immediately followed by, after earlier collisions have resolved" is a stack. Push each asteroid; before pushing a left-mover, resolve it against whatever right-movers are on top. The resolution can cascade: a big left-mover may destroy several right-movers in turn, and the stack handles that in the while loop.
Three outcomes per comparison, and getting all three right is the problem: the top is smaller (it dies, keep comparing), equal (both die, the incoming one stops), or larger (the incoming one dies).
Approach
- For each asteroid, assume it survives.
- While it is a left-mover and the stack top is a right-mover: destroy the smaller, or both if equal, updating survival.
- Push it if it survived.
Dry Run
asteroids = [5,10,-5]
5 stack empty push [5]
10 right-mover, no clash push [5,10]
-5 left-mover vs top 10
|−5| = 5 < 10 -> the incoming one dies
[5,10]
answer [5,10]
asteroids = [8,-8]
8 push [8]
-8 |−8| == 8 -> both destroyed, incoming stops []
answer []
asteroids = [10,2,-5]
10, 2 pushed [10,2]
-5 vs 2: 5 > 2 -> pop 2, keep comparing [10]
-5 vs 10: 5 < 10 -> incoming dies [10]
answer [10]Complexity
- Time — O(n): each asteroid is pushed at most once and popped at most once, so the inner
whileis amortised constant despite looking nested. - Space — O(n): the stack, which holds everything when no collisions occur.
Common Pitfalls
- Mishandling the equal case. Both asteroids are destroyed, so pop and mark the incoming one dead — doing only one of the two is the most common bug.
- Comparing signed values rather than magnitudes. The left-mover's size is
-a. - Checking only that the stack is non-empty, without requiring the top to be a right-mover. Two left-movers never collide.
- Pushing the incoming asteroid before resolving collisions.
- Continuing to compare after the incoming asteroid has died, which can destroy survivors.
Full Solution — all languages
class Solution:
def asteroidCollision(self, nums):
stack = []
for a in nums:
alive = True
while alive and a < 0 and stack and stack[-1] > 0:
if stack[-1] < -a:
stack.pop()
elif stack[-1] == -a:
stack.pop()
alive = False
else:
alive = False
if alive:
stack.append(a)
return stackimport java.util.*;
class Solution {
public int[] asteroidCollision(int[] nums) {
Deque<Integer> stack = new ArrayDeque<>();
for (int a : nums) {
boolean alive = true;
while (alive && a < 0 && !stack.isEmpty() && stack.peekLast() > 0) {
if (stack.peekLast() < -a) stack.pollLast();
else if (stack.peekLast() == -a) {
stack.pollLast();
alive = false;
} else alive = false;
}
if (alive) stack.addLast(a);
}
int[] r = new int[stack.size()];
int i = 0;
for (int x : stack) r[i++] = x;
return r;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> asteroidCollision(vector<int>& nums) {
vector<int> stack;
for (int a : nums) {
bool alive = true;
while (alive && a < 0 && !stack.empty() && stack.back() > 0) {
if (stack.back() < -a) stack.pop_back();
else if (stack.back() == -a) {
stack.pop_back();
alive = false;
} else alive = false;
}
if (alive) stack.push_back(a);
}
return stack;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var asteroidCollision = function(nums) {
const stack = [];
for (const a of nums) {
let alive = true;
while (alive && a < 0 && stack.length && stack[stack.length - 1] > 0) {
if (stack[stack.length - 1] < -a) stack.pop();
else if (stack[stack.length - 1] === -a) {
stack.pop();
alive = false;
} else alive = false;
}
if (alive) stack.push(a);
}
return stack;
};