Asteroid Collision - Problem
Imagine a row of asteroids floating in space, each with a specific size and direction. In this cosmic simulation, we need to determine what happens when these space rocks collide!
You're given an array asteroids where:
- Positive values represent asteroids moving right โ
- Negative values represent asteroids moving left โ
- The absolute value represents the asteroid's size
- All asteroids move at the same speed
Collision Rules:
- When two asteroids meet, the smaller one explodes ๐ฅ
- If both asteroids are the same size, both explode ๐ฅ๐ฅ
- Asteroids moving in the same direction will never collide
Goal: Return the final state of asteroids after all collisions have occurred.
Example: [5, 10, -5] โ The asteroid of size 10 moving right collides with size 5 moving left. Size 10 survives, so result is [5, 10].
Input & Output
example_1.py โ Basic Collision
$
Input:
[5, 10, -5]
โบ
Output:
[5, 10]
๐ก Note:
The asteroid of size 10 moving right collides with size 5 moving left. Since 10 > 5, the left-moving asteroid explodes and we're left with [5, 10].
example_2.py โ Multiple Collisions
$
Input:
[8, -8]
โบ
Output:
[]
๐ก Note:
The asteroid of size 8 moving right collides with size 8 moving left. Since they're equal size, both explode, leaving an empty array.
example_3.py โ Chain Reaction
$
Input:
[10, 2, -5]
โบ
Output:
[10]
๐ก Note:
Size 2 (right) meets size 5 (left): 5 wins. Then size 10 (right) meets size 5 (left): 10 wins. Final result: [10].
Visualization
Tap to expand
Understanding the Visualization
1
Setup Stack
Initialize empty stack to hold surviving right-moving asteroids
2
Process Right-Movers
Add right-moving asteroids to stack - they're safe for now
3
Collision Time!
Left-moving asteroid arrives and battles stack contents
4
Chain Reaction
Continue collisions until no more conflicts exist
5
Final State
Stack contains all surviving asteroids in correct order
Key Takeaway
๐ฏ Key Insight: Stack naturally models the collision process - right-moving asteroids wait in stack until left-moving ones arrive to challenge them!
Time & Space Complexity
Time Complexity
O(n)
Each asteroid is pushed and popped from stack at most once, giving us linear time
โ Linear Growth
Space Complexity
O(n)
Stack can hold up to n asteroids in worst case (all moving right)
โก Linearithmic Space
Constraints
- 2 โค asteroids.length โค 104
- -1000 โค asteroids[i] โค 1000
- asteroids[i] โ 0 (no stationary asteroids)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code