735. Asteroid Collision
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to simulate the collision of asteroids moving in a single row. Asteroids are represented by integers: the sign indicates direction (positive for right, negative for left) and the absolute value indicates size. A collision occurs only when a right-moving asteroid is followed by a left-moving one. The outcome of a collision depends on the asteroids' sizes:
Solution
Asteroid Collision in Python
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for ast in asteroids:
# This while loop handles collisions.
# It continues as long as a collision is possible (stack has a right-mover,
# 'ast' is a left-mover) and 'ast' keeps winning.
while stack and ast < 0 and stack[-1] > 0:
# Collision occurs
if stack[-1] < -ast:
# Top of stack is smaller, gets destroyed.
# Current asteroid 'ast' continues to the next element on the stack.
stack.pop()
continue
elif stack[-1] == -ast:
# Both are the same size, both destroyed.
stack.pop()
# If stack[-1] >= -ast, the incoming 'ast' is destroyed.
# We break from the collision-check loop.
break
else:
# This 'else' belongs to the 'while' loop.
# It executes only if the while loop terminates naturally (not by 'break').
# This means 'ast' survived all potential collisions (or there were none).
stack.append(ast)
return stack
Asteroid Collision in Java
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int[] asteroidCollision(int[] asteroids) {
// Use a Deque as a stack for efficiency.
Deque<Integer> stack = new ArrayDeque<>();
for (int ast : asteroids) {
boolean addAst = true;
// Collision check loop
while (!stack.isEmpty() && ast < 0 && stack.peek() > 0) {
if (stack.peek() < -ast) {
// Top asteroid on stack is smaller and gets destroyed.
stack.pop();
// The incoming asteroid 'ast' continues to check against the new top.
continue;
} else if (stack.peek() == -ast) {
// Both asteroids are the same size, both destroyed.
stack.pop();
}
// If top is same size or larger, the incoming asteroid is destroyed.
// We break the loop and prevent 'ast' from being added.
addAst = false;
break;
}
if (addAst) {
stack.push(ast);
}
}
// Convert the stack (Deque) to an int array.
// The elements are popped from the stack, so we fill the array from the end.
int[] result = new int[stack.size()];
for (int i = stack.size() - 1; i >= 0; i--) {
result[i] = stack.pop();
}
return result;
}
}
Asteroid Collision in C++
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> stack;
for (int ast : asteroids) {
bool add_ast = true;
while (!stack.empty() && ast < 0 && stack.back() > 0) {
// Collision occurs
if (stack.back() < -ast) {
// Top asteroid is smaller and is destroyed.
stack.pop_back();
// The incoming asteroid 'ast' continues to check against the new top.
continue;
} else if (stack.back() == -ast) {
// Both asteroids are the same size and are destroyed.
stack.pop_back();
}
// If top is same size or larger, incoming asteroid is destroyed.
// We break the loop and prevent 'ast' from being added.
add_ast = false;
break;
}
if (add_ast) {
stack.push_back(ast);
}
}
return stack;
}
};
Asteroid Collision in TypeScript
function asteroidCollision(asteroids: number[]): number[] {
const stack: number[] = [];
for (const ast of asteroids) {
let addAst = true;
// Collision check loop
while (stack.length > 0 && ast < 0 && stack[stack.length - 1] > 0) {
const top = stack[stack.length - 1];
if (top < -ast) {
// Top asteroid is smaller and gets destroyed.
stack.pop();
// The incoming asteroid 'ast' continues to check against the new top.
continue;
} else if (top === -ast) {
// Both asteroids are the same size, both destroyed.
stack.pop();
}
// If top is same size or larger, the incoming asteroid is destroyed.
// We break the loop and prevent 'ast' from being added.
addAst = false;
break;
}
if (addAst) {
stack.push(ast);
}
}
return stack;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.