Asteroid Collision

Medium Stack & Queue

asteroids is a row of asteroids, read from left to right. A positive number is an asteroid flying right and a negative one an asteroid flying left; the number without its sign is the asteroid's size. They all fly at one speed.

An asteroid flying right crashes into the asteroids flying left that reach it from its right. In a crash the smaller asteroid is destroyed, and two of one size are both destroyed; the winner flies on and may crash again. Asteroids flying the same way, or away from each other, never crash.

Return the asteroids still flying once no more crashes can happen, in their order from left to right.

Example 1

Input: asteroids = [4,-7,9,3,-5,1,-1]
Output: [-7,9]

4 flies right into -7, the larger, and is destroyed; -7 flies on to the left with nothing to meet. -5 destroys 3, then 9 destroys -5. 1 and -1 are of one size, so both go. -7 and 9 are left, flying apart.

Example 2

Input: asteroids = [6,6,-6]
Output: [6]

Example 3

Input: asteroids = [-4,5,-2,-9,9]
Output: [-4,-9,9]

Constraints

  • 1 ≤ asteroids.length ≤ 5 × 10⁵
  • -10⁹ ≤ asteroids[i] ≤ 10⁹ and asteroids[i] ≠ 0

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Stack & Queue

All Stack & Queue problems