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
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
Example 3
Constraints
1 ≤ asteroids.length ≤ 5 × 10⁵-10⁹ ≤ asteroids[i] ≤ 10⁹andasteroids[i] ≠ 0
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
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 roundMore Stack & Queue
- Valid ParenthesesAI round · Easy
- Daily TemperaturesAI round · Medium
- Decode StringAI round · Medium
- Largest Rectangle in HistogramHard
- Maximal RectangleHard