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
Asteroid Collision Simulation5โ†’10โ†’โ†5COLLISION!510Survivors
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Stack can hold up to n asteroids in worst case (all moving right)

n
2n
โšก Linearithmic Space

Constraints

  • 2 โ‰ค asteroids.length โ‰ค 104
  • -1000 โ‰ค asteroids[i] โ‰ค 1000
  • asteroids[i] โ‰  0 (no stationary asteroids)
Asked in
Amazon 45 Google 32 Meta 28 Microsoft 22 Apple 18
89.6K Views
High Frequency
~18 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