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
Asteroid Collision INPUT 5 10 -5 Green arrow = Right (+) Red arrow = Left (-) asteroids = [5, 10, -5] Size = |value|, Sign = direction Process left to right using a stack Collision: opposite directions ALGORITHM STEPS 1 Push 5 Positive, goes right [5] 2 Push 10 Positive, goes right [5, 10] 3 Process -5 Negative (left), collision! 10 vs |-5|: 10 > 5 10 X 5 -5 explodes 10 survives 4 Done Return stack contents [5, 10] Time: O(n) | Space: O(n) FINAL RESULT 5 10 Both moving right - no more collisions Output: [5, 10] OK - Verified Asteroid -5 destroyed by larger asteroid 10 Key Insight: Use a stack to track right-moving asteroids. When a left-moving asteroid appears, simulate collisions with the stack top until either the left asteroid is destroyed or the stack is empty/has a left-mover. Collisions only occur when: positive (right) meets negative (left). Same direction = no collision. TutorialsPoint - Asteroid Collision | Optimal Stack-Based Solution
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
158.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen