Asteroid Collision - Problem
We are given an array asteroids of integers representing asteroids in a row. The indices represent their relative position in space.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Input & Output
Example 1 — Basic Collision
$
Input:
asteroids = [5,10,-5]
›
Output:
[5,10]
💡 Note:
The 10 and -5 collide. Since 10 > 5, the -5 explodes. The 5 and 10 never collide.
Example 2 — Chain Reaction
$
Input:
asteroids = [8,-8]
›
Output:
[]
💡 Note:
The 8 and -8 collide and both explode, leaving an empty array.
Example 3 — Multiple Collisions
$
Input:
asteroids = [10,2,-5]
›
Output:
[10]
💡 Note:
The 2 and -5 collide, -5 wins. Then 10 and -5 collide, 10 wins.
Constraints
- 2 ≤ asteroids.length ≤ 104
- -1000 ≤ asteroids[i] ≤ 1000
- asteroids[i] ≠ 0
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of asteroids with size and direction [5, 10, -5]
2
Collision
Right-moving (10) meets left-moving (-5)
3
Result
Larger asteroid survives: [5, 10]
Key Takeaway
🎯 Key Insight: Use a stack to handle collisions between right-moving and left-moving asteroids efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code