LeetCode #735 Medium

Asteroid Collision

Asteroid Collision is LeetCode 735 (Medium). asteroids lists asteroids in a row. The sign of each value is its direction (positive moves right, negative moves left) and the absolute value is its size. All of them move at the same speed.

  • When two asteroids meet, the smaller one explodes. If they are the same size, both explode.
  • Two asteroids moving the same way never meet.

Return the asteroids that are left after every collision, in their original order.

Constraints
  • 2 <= asteroids.length <= 10⁴
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0
stackarraysimulation
Open on LeetCode ↗
02

Intuition

Only one arrangement can crash: a right-mover with a left-mover somewhere after it. A left-mover followed by a right-mover is flying apart.

Scan left to right and keep the survivors so far. A new right-mover cannot hit any kept asteroid yet. A new left-mover meets the kept right-movers starting with the newest one, because that one is closest to it. Newest first is exactly how a stack works.

So the left-mover pops smaller right-movers off the top until it explodes, meets one of equal size, or has no right-mover in front of it. In that last case nothing can ever reach it, so it stays.

How to spot this pattern

Each new item either cancels the newest kept items or is kept itself, and the order of what is left matters: that is a stack scan, the same shape as Valid Parentheses or Removing Stars From a String.

03

Approach

Try it first

Before reading on, decide which pairs of signs can ever meet. Then decide which kept asteroid a new left-mover hits first, and what happens after it wins. Aim for O(n) time.

1

Keep the survivors on a stack

Walk the array once. st holds the asteroids that have survived so far, in their original order, with the newest on top. A right-mover is pushed straight away: everything kept is behind it or flying away from it.

2

Let a left-mover fight the top

While the new asteroid a is negative and the top is positive, compare sizes:

  • top smaller than -a: pop it and keep fighting, because the next right-mover is now in front;
  • same size: pop it, and a explodes too;
  • top bigger: a explodes and the stack is left alone.
3

Push the left-mover if it survived

If a is still alive, the stack is empty or its top is another left-mover. Nothing behind it can ever catch it, so push it. When the scan ends, the stack from bottom to top is the answer, already in order.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def asteroidCollision(self, asteroids):
▶3 st = []
▶4 for a in asteroids:
▶5 alive = True
▶6 while alive and a < 0 and st and st[-1] > 0:
▶7 if st[-1] < -a:
▶8 st.pop()
▶9 elif st[-1] == -a:
▶10 st.pop()
▶11 alive = False
▶12 else:
▶13 alive = False
▶14 if alive:
▶15 st.append(a)
▶16 return st
still to come1025survivors, top on the rightemptyempty stack, 3 asteroids to read
asteroids[10, 2, -5]
stack[]
Each tile shows an asteroid's size, and the arrow shows which way it flies. Read them left to right and keep the survivors on a stack, newest on the right.
still to come25survivors, top on the right10topsize 10 flying right → push
a10moving right
stack[10]
Push 10. It flies right, so it cannot hit anything already kept. A later left-mover may still reach it.
still to come5survivors, top on the right102topsize 2 flying right → push
a2moving right
stack[10, 2]
Push 2. It flies right, so it cannot hit anything already kept. A later left-mover may still reach it.
still to comenonesurvivors, top on the right102topvs5size 2 vs 5 → 2 explodes
top2moving right
a-5moving left
resultpop 2
The top asteroid flies right and the new one flies left, so they meet. Size 2 is smaller than 5, so the top explodes. The new asteroid keeps going and next faces whatever is under it.
still to comenonesurvivors, top on the right10topvs5size 10 vs 5 → 5 explodes
top10moving right
a-5moving left
resultstack unchanged
Size 10 is bigger than 5, so the new asteroid explodes and the stack stays as it is. Anything under the top is behind it and safe.
still to comenonesurvivors, top on the right10top1 left → answer 10
answer[10]
Every asteroid has been read. The stack from bottom to top is the survivors in their original order, so it is returned as it is.
05

Common pitfalls

Comparing sizes without checking directions

✗ Wrong
while st and abs(st[-1]) < abs(a):
    st.pop()
✓ Right
while alive and a < 0 and st and st[-1] > 0:

Two left-movers never meet, but a size-only test lets the bigger one destroy the smaller. On [-1, -2] it returns [-2] instead of [-1, -2].

Fighting only once with if

✗ Wrong
if a < 0 and st and st[-1] > 0:
    ...
✓ Right
while alive and a < 0 and st and st[-1] > 0:
    ...

A big left-mover that wins keeps flying and hits the next right-mover too. On [1, 2, 3, -5] a single if returns [1, 2, -5]; the right answer is [-5].

Pushing after a same-size crash

✗ Wrong
elif st[-1] == -a:
    st.pop()
    break
...
st.append(a)
✓ Right
elif st[-1] == -a:
    st.pop()
    alive = False
...
if alive:
    st.append(a)

Equal sizes destroy both. break leaves the loop but still reaches the push, so on [8, -8] the result is [-8] instead of []. The alive flag keeps "stop fighting" and "survived" apart.

06

Edge cases

Left-movers at the front, right-movers at the back

For [-2, -1, 1, 2] every left-mover finds an empty stack or another left-mover on top, and every right-mover is pushed. Nothing meets, so the input comes back unchanged.

07

Complexity

Time
O(n)
Space
O(n)
The inner loop can pop many asteroids for one left-mover, but each asteroid is pushed at most once and popped at most once over the whole scan, so all the pops together cost O(n). The stack holds every asteroid when none collide, for example when all move right.
08

Asteroid Collision FAQ

Does the gap between two asteroids matter?

No. All asteroids move at the same speed, so a right-mover and a left-mover after it close the gap at a steady rate and always meet, however far apart they start. That is why the array only needs to be read in order, with no positions or times.

Can it be done without an extra stack?

Yes. Use the input array itself as the stack: keep a write index top, overwrite asteroids[top] to push and decrease top to pop, then return the first top values. The extra space drops to O(1) besides the output, and the logic is unchanged.