Asteroid Collision Visualizer & Solution | Rulcode
Loading problem details...
228. Asteroid Collision
PRO
Medium
Topics
Companies
Hint
Understand Before Coding
Loading visualization...
Visualize This Problem
Open Visualizer
Draw Your Approach
Draw
Example 1:
Input:asteroids = [5,10,-5]
Output:[5,10]
Explanation:The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input:asteroids = [8,-8]
Output:[]
Explanation:The 8 and -8 collide exploding each other.
Example 3:
Input:asteroids = [10,2,-5]
Output:[10]
Explanation:The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Example 4:
Input:asteroids = [3,5,-6,2,-1,4]
Output:[-6,2,4]
Explanation:The asteroid -6 makes the asteroid 3 and 5 explode, and then continues going left. On the other side, the asteroid 2 destroys -1. Since 2 and 4 are both moving right, they never collide.
Constraints:
•
•
•
Time Complexity
O(N)
Space Complexity
O(N)
Step 1 / 21
Speed: 1.0x
Asteroid Collision (Stack Logic)
Input Asteroid Track
+10→
+2→
-5←
Asteroid Stack
Stack Empty (No Asteroids)
Commentary
Given an array of asteroids, positive ones move right (→) and negative ones move left (←). When they meet, they collide and the smaller one explodes; if equal, both explode.