Asteroid Collision (LeetCode 735): Solution and Explanation

Medium
Array
Stack
Simulation

A row of asteroids moves along a line, where the sign gives the direction (positive means right, negative means left) and the absolute value gives the size. When two meet, the smaller one explodes, and equal sizes destroy each other. Return what is left once no more collisions can happen.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

First pin down when a collision can actually happen. Two asteroids moving the same way never meet. An asteroid moving left that sits to the left of one moving right is flying away from it, so they never meet either. The only collision is a right-mover followed somewhere later by a left-mover.

A naive simulation would scan the array for any adjacent right-then-left pair, resolve it, and rescan until nothing changes. That can cost O(n²) because each pass may resolve only one collision.

Instead, process asteroids from left to right and keep the survivors so far on a stack. The survivors never collide with each other, so the only thing a new asteroid can hit is the top of the stack. If the new one moves right, or the top moves left, or the stack is empty, there is no collision and it is simply pushed.

If the new asteroid moves left and the top moves right, they fight. If the top is smaller, it explodes and the new asteroid keeps going, so you check the next top. If they are equal, both explode. If the top is larger, the new asteroid explodes. This repeated popping is why a stack fits so well: one big left-mover can sweep away a whole run of small right-movers in a single arrival.

Approach: Stack simulation

  1. Create an empty stack for the asteroids that have survived so far.
  2. For each asteroid, loop while the stack is non-empty and asteroid < 0 < stack[-1], meaning a collision is happening.
  3. If the top is smaller than the incoming asteroid's size, pop it and continue so the incoming asteroid can hit the next one.
  4. If the top has the same size, pop it, then break because the incoming asteroid is destroyed too.
  5. If the top is larger, just break, since only the incoming asteroid explodes.
  6. If the loop ended without a break, the while-else branch pushes the incoming asteroid. Return the stack at the end.

Step-by-step example

asteroids = [10,2,-5]
  1. The stack is empty, so 10 is pushed. The stack is [10].
  2. 2 moves right, so there is no collision and it is pushed. The stack is [10,2].
  3. -5 moves left and the top 2 moves right, so they collide. The top 2 is smaller than 5, so 2 is popped and the loop continues.
  4. Now the top is 10, which is larger than 5. The incoming -5 explodes and the loop breaks, so nothing is pushed.
  5. The input is exhausted and the answer is [10].

Code: Python, Java, C++

1class Solution:
2    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
3        stack = []
4        for asteroid in asteroids:
5            while stack and asteroid < 0 < stack[-1]:
6                if stack[-1] < -asteroid:
7                    stack.pop()
8                    continue
9                elif stack[-1] == -asteroid:
10                    stack.pop()
11                break
12            else:
13                stack.append(asteroid)
14        return stack

Time and space complexity

Time

O(n)

Each asteroid is pushed at most once and popped at most once, so the total work across all the inner loops is linear in the number of asteroids.

Space

O(n)

In the worst case nothing collides, for example when all asteroids move the same way, and the stack holds every one of them.

Other approaches

Repeated pass simulation (time O(n²), space O(n))

Scan the array for an adjacent pair with a positive value followed by a negative one, resolve that collision, and repeat until a full pass finds none. It mirrors the physical picture directly but can need a pass per collision.

Common mistakes

  • Treating a left-mover followed by a right-mover, such as [-2,3], as a collision. Those two move apart, so both survive.
  • Forgetting the equal-size case, where both asteroids must vanish. With [8,-8] the answer is empty, not [8] or [-8].
  • Using if instead of while, which lets an incoming asteroid destroy only one stack element even when it should destroy several.
  • Pushing the incoming asteroid after it has been destroyed. In Python the while-else handles this, since the else runs only when the loop ends without a break.

Frequently asked questions

Why use a stack for Asteroid Collision?

Survivors never collide with each other, so a new asteroid can only hit the most recent surviving right-mover. That last-in, first-out access is exactly what a stack gives you.

What does while else do in the Python solution?

The else block runs only if the while loop finishes because its condition became false, not because of a break. Here it means the incoming asteroid survived every collision, so it gets pushed.

Why is the time complexity O(n)?

Each asteroid is pushed at most once and popped at most once. Even though one arrival can trigger many pops, the total number of pops over the whole run cannot exceed n.

Do two negative asteroids ever collide?

No. Asteroids moving in the same direction travel at the same speed and never meet, so a run of left-movers just stays in the stack.