Asteroid Collision

medium

You are given an array asteroids; each value is a moving asteroid. Its magnitude is its size and its sign is its direction: positive moves right, negative moves left. All move at the same speed.

Two asteroids collide only when a right-moving one is immediately followed by a left-moving one. The smaller explodes; if they're the same size, both explode. Same-direction asteroids never collide. Return the state of the asteroids after all collisions.

Hints

A collision only happens when a right-mover is immediately followed by a left-mover.
Keep a stack of survivors; push right-movers, and let left-movers fight down the stack.
Compare magnitudes: pop a smaller top, annihilate an equal one, or destroy the incoming asteroid.

Common doubts

A right-mover moves away from everything already on the stack, so it never collides on arrival. Only a left-mover can catch up to the right-movers ahead of it.
It might be destroyed during its collisions. Pushing it first would leave a dead asteroid on the stack.
Every asteroid is pushed at most once and popped at most once across the whole run, so total collision work is linear.

Interview follow-ups

The 'immediately adjacent' collision rule breaks; you'd sort collision events by time and process them in order — an event-driven simulation.
Track indices on the stack and record the survivor/destroyer pair at each collision.

Fun facts

  • This is a discrete-event collision simulation compressed into a single stack pass.
  • The same 'incoming element cascades through the stack' shape appears in expression evaluation and bracket matching.

Asked at

AmazonGoogleMeta
Frequently Sometimes Occasionally
Example 1
Input: asteroids = [5,10,-5]
Output: [5,10]
10 and -5 collide; 10 survives. 5 and 10 move the same way and never collide.
Example 2
Input: asteroids = [8,-8]
Output: []
8 and -8 are equal size, so both explode.
Constraints

- 2 <= asteroids.length <= 10^4 - -1000 <= asteroids[i] <= 1000 - asteroids[i] != 0

Solve this problem →