Community Problem

Asteroid Collision

Difficulty: Medium

Simulate collisions between right- and left-moving asteroids using a stack of survivors, popping while the top loses head-on encounters.

Asteroid Collision

Simulate collisions between right- and left-moving asteroids using a stack of survivors, popping while the top loses head-on encounters.

MEDIUM
Free
stack
simulation
arrays
jamalvargas

By @jamalvargas

December 2, 2025

·

Updated May 18, 2026

1,159 views

20

4.4 (11)

Got asked this on an L5 Google interview loop, and the gotcha was the equal-mass case: the candidate before me had spent 25 minutes debugging an inner loop that double-popped when both asteroids should annihilate. The clean version is a tight stack with one outer for-loop and one inner while-loop.

Asteroid Collision

You are given an integer array asteroids where each non-zero entry represents an asteroid in space. The absolute value is the asteroid's mass; the sign indicates direction (positive moves right, negative moves left). All asteroids start in a row and move at the same speed. When two asteroids collide head-on (a right-mover meets a left-mover), the smaller one (by absolute value) explodes. If they have equal absolute value, both explode. Asteroids moving in the same direction never collide.

Return the state of the asteroids after all collisions resolve.

Examples

Example 1:

  • Input: asteroids = [5, 10, -5]
  • Output: [5, 10]
  • Explanation: 10 and -5 collide; 10 is bigger and survives. 5 and 10 move in the same direction.

Example 2:

  • Input: asteroids = [8, -8]
  • Output: []
  • Explanation: Equal mass, both explode.

Example 3:

  • Input: asteroids = [10, 2, -5]
  • Output: [10]
  • Explanation: 2 and -5 collide, 2 explodes. Then 10 and -5 collide, -5 explodes.

Example 4:

  • Input: asteroids = [-2, -1, 1, 2]
  • Output: [-2, -1, 1, 2]
  • Explanation: Left-movers stay on the left, right-movers stay on the right; no head-on collisions occur.

Constraints

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

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems