15% off all plans & roadmaps Use code
See plansAsteroid Collision
- LeetCode 735
- Medium
- Stack Patterns
- Simulation / Backtracking Helper
Updated
TL;DR: Asteroids move in a row, and a collision happens only when a right-mover sits to the left of a left-mover. A stack of survivors settles each left-mover against the right-movers before it in one left-to-right pass.
Problem
You get an array asteroids of integers that represent asteroids in a row. The index of each asteroid gives its position in space.
The absolute value of each number is the asteroid's size. The sign gives its direction: positive moves right and negative moves left. All asteroids move at the same speed.
Find the state of the asteroids after every collision. When two asteroids meet, the smaller one explodes. If they are the same size, both explode. Two asteroids moving in the same direction never meet.
Example 1
Input: asteroids = [5,10,-5] Output: [5,10] Explanation: The 10 and -5 collide, and the result is 10. The 5 and 10 never collide.
Example 2
Input: asteroids = [8,-8] Output: [] Explanation: The 8 and -8 collide, and both explode.
Example 3
Input: asteroids = [10,2,-5] Output: [10] Explanation: The 2 and -5 collide, and the result is -5. Then the 10 and -5 collide, and the result is 10.
Constraints
2 <= asteroids.length <= 10^4-1000 <= asteroids[i] <= 1000asteroids[i] != 0
Constraints that matter
- n up to 10^4 means an O(n^2) scan with list shifting is about 10^8 basic steps in the worst case, which is too slow for a tight interview budget.
- Values are between -1000 and 1000 and never zero, so the sign alone gives direction and the absolute value gives size.
- Only a positive value followed by a negative value can collide, so you never need to compare two values that move the same way.
- Each asteroid can be destroyed only once, which means one left-to-right pass with a stack can settle every collision.
Hints
Hint 1
Collisions happen only between a right-moving asteroid and a left-moving asteroid that sits to its right.
Hint 2
The true naive method treats the row as a plain list and rescans it until nothing changes.
Solution
Intuition
Collisions happen only between a right-moving asteroid and a left-moving asteroid that sits to its right. A left-mover can only meet the nearest right-movers on its left, and the nearest one is always the most recent survivor. That last-in, first-out order is the stack pattern.
Picture a stack of plates where only the top plate can be touched. Each right-mover is a plate, and an incoming left-mover hits the top plate first, then the next one down.
Process the row from left to right and keep the survivors in a stack. A right-mover is safe the moment it is pushed, because nothing to its right has been processed yet. A left-mover must fight the stack top, then the next one, until it dies or no right-movers remain on the stack.
Two left-movers never meet, so a left-mover that finds an empty stack or a left-moving top stays. The stack then holds only asteroids that move the same way or have settled. Each asteroid is pushed once and popped at most once, which keeps the whole pass linear.
Worked example
Input: asteroids = [10, 2, -5, -15, 20, -20, 5] Output: [-15, 5] Explanation: The 2 dies to -5, and the -5 dies to 10. The -15 then destroys the 10 and survives. The 20 and -20 are equal, so both vanish. The 5 moves right and never meets a survivor, so it stays.
Approach 1: Brute force: rescan for collisions
The true naive method treats the row as a plain list and rescans it until nothing changes. It looks for any adjacent pair where the left value is positive and the right value is negative. It resolves that pair, deletes the loser, and starts the scan again from the beginning.
The restart is needed because a deletion can create a new adjacent pair. In the example, the 2 vanishes and the 10 becomes next to the -5, which is a fresh collision.
Steps
- Copy the input into a working list.
- Scan adjacent pairs from left to right for a positive value followed by a negative value.
- If no such pair exists, return the working list.
- For the first such pair, delete the smaller asteroid, or delete both if they are equal.
- Go back to the scan and start again from index 0.
Dry run
Start with [10, 2, -5, -15, 20, -20, 5].
Pass 1: the first positive-then-negative pair is (2, -5). 2 is smaller, so delete the 2. List: [10, -5, -15, 20, -20, 5].
Pass 2: the pair (10, -5) is first. 10 is bigger, so delete the -5. List: [10, -15, 20, -20, 5].
Pass 3: the pair (10, -15) is first. 10 is smaller, so delete the 10. List: [-15, 20, -20, 5].
Pass 4: the pair (20, -20) is first. They are equal, so delete both. List: [-15, 5].
Pass 5: no positive-then-negative pair exists. Return [-15, 5].
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Let n be the length of the array. Each pass scans at most n - 1 adjacent pairs and shifts up to n elements on a deletion, so one pass costs O(n). Each pass removes at least one asteroid, so there are at most n - 1 passes. Multiplying O(n) passes by O(n) work per pass gives O(n^2). The working copy holds up to n values, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
cur = list(asteroids)
while True:
hit = -1
for i in range(len(cur) - 1):
if cur[i] > 0 and cur[i + 1] < 0:
hit = i
break
if hit == -1:
return cur
a, b = cur[hit], cur[hit + 1]
if a > -b:
del cur[hit + 1]
elif a < -b:
del cur[hit]
else:
del cur[hit:hit + 2]JavaTested in our runner
import java.util.*;
class Solution {
public int[] asteroidCollision(int[] asteroids) {
List<Integer> cur = new ArrayList<>();
for (int a : asteroids) cur.add(a);
boolean found = true;
while (found) {
found = false;
for (int i = 0; i + 1 < cur.size(); i++) {
int a = cur.get(i), b = cur.get(i + 1);
if (a > 0 && b < 0) {
found = true;
if (a > -b) cur.remove(i + 1);
else if (a < -b) cur.remove(i);
else { cur.remove(i + 1); cur.remove(i); }
break;
}
}
}
int[] res = new int[cur.size()];
for (int i = 0; i < res.length; i++) res[i] = cur.get(i);
return res;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> cur = asteroids;
bool found = true;
while (found) {
found = false;
for (int i = 0; i + 1 < (int)cur.size(); i++) {
int a = cur[i], b = cur[i + 1];
if (a > 0 && b < 0) {
found = true;
if (a > -b) cur.erase(cur.begin() + i + 1);
else if (a < -b) cur.erase(cur.begin() + i);
else cur.erase(cur.begin() + i, cur.begin() + i + 2);
break;
}
}
}
return cur;
}
};JavaScriptTested in our runner
/**
* @param {number[]} asteroids
* @return {number[]}
*/
var asteroidCollision = function(asteroids) {
const cur = asteroids.slice();
let found = true;
while (found) {
found = false;
for (let i = 0; i + 1 < cur.length; i++) {
const a = cur[i], b = cur[i + 1];
if (a > 0 && b < 0) {
found = true;
if (a > -b) cur.splice(i + 1, 1);
else if (a < -b) cur.splice(i, 1);
else cur.splice(i, 2);
break;
}
}
}
return cur;
};GoTested in our runner
func asteroidCollision(asteroids []int) []int {
cur := make([]int, len(asteroids))
copy(cur, asteroids)
found := true
for found {
found = false
for i := 0; i+1 < len(cur); i++ {
a, b := cur[i], cur[i+1]
if a > 0 && b < 0 {
found = true
if a > -b {
cur = append(cur[:i+1], cur[i+2:]...)
} else if a < -b {
cur = append(cur[:i], cur[i+1:]...)
} else {
cur = append(cur[:i], cur[i+2:]...)
}
break
}
}
}
return cur
}C#Tested in our runner
public class Solution {
public int[] asteroidCollision(int[] asteroids) {
List<int> cur = new List<int>(asteroids);
bool found = true;
while (found) {
found = false;
for (int i = 0; i + 1 < cur.Count; i++) {
int a = cur[i], b = cur[i + 1];
if (a > 0 && b < 0) {
found = true;
if (a > -b) cur.RemoveAt(i + 1);
else if (a < -b) cur.RemoveAt(i);
else { cur.RemoveAt(i + 1); cur.RemoveAt(i); }
break;
}
}
}
return cur.ToArray();
}
}The Simulation / Backtracking Helper infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Simulation / Backtracking Helper
Part of Stack Patterns
Approach 2: One-pass stackOptimalSimulation / Backtracking Helper
What's slow in the brute force is repeated work. Every restart walks the list from index 0, even though the prefix before the collision did not change. Each deletion also shifts the rest of the list.
The insight that fixes it: process the row once from left to right and keep the survivors in a stack. The stack top is always the nearest right-mover that a new left-mover can reach. When the top dies or is removed, the next top is the next candidate, so the search never restarts.
Why it is correct. The stack always holds exactly the asteroids that can still meet something further right, kept in left-to-right order. A left-mover that stays alive has beaten every right-mover it reached, so later asteroids cannot change that outcome.
Steps
- Create an empty stack for survivors.
- For each asteroid, set a flag alive to true.
- While alive, the asteroid moves left, and the stack top moves right: compare absolute sizes.
- If the top is smaller, pop it and keep looping. If they are equal, pop the top and set alive to false. If the top is bigger, set alive to false.
- If the asteroid is still alive after the loop, push it.
- Return the stack contents from bottom to top as the answer.
Dry run
| Step | Next asteroid | Stack before | Action | Stack after |
|---|---|---|---|---|
| 1 | 10 | [] | Stack is empty, push | [10] |
| 2 | 2 | [10] | Right-mover, push | [10, 2] |
| 3 | -5 | [10, 2] | 2 is smaller, pop. 10 is bigger, -5 dies | [10] |
| 4 | -15 | [10] | 10 is smaller, pop. Stack empty, push | [-15] |
| 5 | 20 | [-15] | Right-mover, push | [-15, 20] |
| 6 | -20 | [-15, 20] | 20 equals 20, pop and both die | [-15] |
| 7 | 5 | [-15] | Top moves left, so no collision. Push | [-15, 5] |
The final stack is [-15, 5], which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of the array. Each asteroid is pushed at most once and popped at most once, so the total number of pops across the run is at most n. The inner loop does one pop per iteration, and earlier pushes pay for those pops. The outer loop runs n times, so total time is O(n). The stack never holds more than n values, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for a in asteroids:
alive = True
# Collide only when the stack top moves right and a moves left
while alive and a < 0 and stack and stack[-1] > 0:
top = stack[-1]
if top < -a:
stack.pop()
elif top == -a:
stack.pop()
alive = False
else:
alive = False
if alive:
stack.append(a)
return stackJavaTested in our runner
import java.util.*;
class Solution {
public int[] asteroidCollision(int[] asteroids) {
int[] stack = new int[asteroids.length];
int size = 0;
for (int a : asteroids) {
boolean alive = true;
// Collide only when the stack top moves right and a moves left
while (alive && a < 0 && size > 0 && stack[size - 1] > 0) {
int top = stack[size - 1];
if (top < -a) {
size--;
} else if (top == -a) {
size--;
alive = false;
} else {
alive = false;
}
}
if (alive) stack[size++] = a;
}
return Arrays.copyOf(stack, size);
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> st;
for (int a : asteroids) {
bool alive = true;
// Collide only when the stack top moves right and a moves left
while (alive && a < 0 && !st.empty() && st.back() > 0) {
int top = st.back();
if (top < -a) {
st.pop_back();
} else {
if (top == -a) st.pop_back();
alive = false;
}
}
if (alive) st.push_back(a);
}
return st;
}
};JavaScriptTested in our runner
/**
* @param {number[]} asteroids
* @return {number[]}
*/
var asteroidCollision = function(asteroids) {
const stack = [];
for (const a of asteroids) {
let alive = true;
// Collide only when the stack top moves right and a moves left
while (alive && a < 0 && stack.length > 0 && stack[stack.length - 1] > 0) {
const top = stack[stack.length - 1];
if (top < -a) {
stack.pop();
} else {
if (top === -a) stack.pop();
alive = false;
}
}
if (alive) stack.push(a);
}
return stack;
};GoTested in our runner
func asteroidCollision(asteroids []int) []int {
stack := []int{}
for _, a := range asteroids {
alive := true
// Collide only when the stack top moves right and a moves left
for alive && a < 0 && len(stack) > 0 && stack[len(stack)-1] > 0 {
top := stack[len(stack)-1]
if top < -a {
stack = stack[:len(stack)-1]
} else {
if top == -a {
stack = stack[:len(stack)-1]
}
alive = false
}
}
if alive {
stack = append(stack, a)
}
}
return stack
}C#Tested in our runner
public class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<int> stack = new Stack<int>();
foreach (int a in asteroids) {
bool alive = true;
// Collide only when the stack top moves right and a moves left
while (alive && a < 0 && stack.Count > 0 && stack.Peek() > 0) {
int top = stack.Peek();
if (top < -a) {
stack.Pop();
} else {
if (top == -a) stack.Pop();
alive = false;
}
}
if (alive) stack.Push(a);
}
int[] res = stack.ToArray();
Array.Reverse(res);
return res;
}
}Common mistakes
while stack and a < 0with no check onstack[-1] > 0. Two left-movers never meet, so[-2, -5]must stay unchanged. Check the sign of the stack top before comparing sizes.- Comparing signed values, such as
stack[-1] > a. On[2, -5]this keeps the 2 when the -5 should win. Compare absolute values. - Pushing the current asteroid after an equal-size pop. On
[8, -8]the -8 would survive wrongly. Setaliveto false when the sizes match. - Popping only once per asteroid instead of looping. On
[2, 3, -10]the 3 and the 2 must both die, leaving[-10]. Keep looping while the asteroid is alive and the top moves right. - In the brute force, removing only one side of an equal pair. Deleting only the left 8 from
[8, -8]leaves[-8]. Equal sizes remove both asteroids. - Filling the Java or C# result array from the top of the stack. That reverses the order, so
[5, 10]would come back as[10, 5]. Copy from the bottom of the stack to the top.
Edge cases
[1, 2, 3]with all right-movers: no collision, so the output is[1, 2, 3].[-1, -2]with all left-movers: they move apart from the same side and never meet, so the output is unchanged.[5, -5]with equal sizes: both explode, so the output is[].[-5, 5]with a left-mover before a right-mover: they move apart, so the output is[-5, 5].[3, -1]with a larger right-mover: the -1 explodes and the output is[3].- Length 10^4 with many right-movers followed by one large left-mover: the stack version does a single pass, while the brute force deletes many elements and rescans.
Follow-ups interviewers ask
- What if you need to return the original indices of the survivors instead of their values?
- Push the index along with the value, or push the index and look up the value through the array. Collision logic still compares absolute values, so the rest of the code does not change. Output the stored indices in stack order.
- Can you solve it in O(1) extra space?
- Yes, if you may change the input. Use the input array as the stack with a write index k, where k never passes the read index i. Read asteroids[i] before writing at position k, so no unread value is overwritten. The extra space is O(1), but the input array is modified.
- What if the array does not fit in memory?
- Process the input in chunks and keep only the stack between chunks. The stack holds the survivors, which can still be up to n values if every asteroid moves right. Chunking bounds the input memory, but the output can still be large.
Asteroid Collision FAQ
What is the time complexity of Asteroid Collision?
The one-pass stack solution runs in O(n) time, because each asteroid is pushed once and popped at most once. The brute force rescan runs in O(n^2) time because it can restart the scan up to n times and shift the list on each deletion.
Why use a stack for Asteroid Collision?
Collisions only happen between a left-mover and the nearest right-mover to its left. That nearest survivor is the most recently pushed right-mover, which is the stack top. A stack gives you that element in O(1) and lets you remove it in O(1) when it dies.
Can Asteroid Collision be solved in O(1) extra space?
Yes, if you may modify the input array. Reuse the array as the stack with a write pointer, and the output is the first k values. If the input must stay intact, you need O(n) extra space for the survivors.
Does Asteroid Collision need backtracking, recursion, sorting, dynamic programming or a tree?
No. The result is fixed once the left-to-right order is fixed, so there are no choices to explore. Sorting breaks the order that decides who meets whom, and a tree is not needed for a flat row. Recursion can express the same pop loop, but an explicit stack avoids deep call chains.
Why does the answer change if I sort the asteroids by size first?
Collisions depend on neighbours in the row, so sorting moves asteroids next to asteroids they never meet. A large left-mover at the far right would then appear to hit small right-movers at the far left. Keep the original order.
Asked at
See which companies ask this — Pro
Related problems
- Simplify Path · same technique: Simulation / Backtracking Helper
- Decode String · same technique: Simulation / Backtracking Helper
- Reconstruct Itinerary · same technique: Simulation / Backtracking Helper
- Baseball Game · same technique: Simulation / Backtracking Helper
- Crawler Log Folder · same technique: Simulation / Backtracking Helper
- Evaluate Reverse Polish Notation · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns
- Car Fleet · same pattern: Stack Patterns
- Valid Parenthesis String · same pattern: Stack Patterns