#735
Asteroid Collision
MediumArrayStackSimulationStackSimulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a stack allows us to efficiently manage the collisions. We can push asteroids into the stack and handle collisions as we encounter them, ensuring we only process each asteroid once.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty stack to keep track of surviving asteroids.
- 2Step 2: Iterate through each asteroid in the array.
- 3Step 3: For each asteroid, check if it collides with the top of the stack (if the top is positive and the current is negative).
- 4Step 4: Resolve collisions by comparing sizes and updating the stack accordingly.
- 5Step 5: If no collision occurs, push the asteroid onto the stack.
solution.py15 lines
1# Full working Python code
2
3def asteroidCollision(asteroids):
4 stack = []
5 for asteroid in asteroids:
6 while stack and asteroid < 0 < stack[-1]:
7 if abs(asteroid) > abs(stack[-1]):
8 stack.pop()
9 continue
10 elif abs(asteroid) == abs(stack[-1]):
11 stack.pop()
12 break
13 else:
14 stack.append(asteroid)
15 return stackℹ
Complexity note: The time complexity is O(n) because each asteroid is processed once, and the stack operations (push/pop) are O(1). The space complexity is O(n) due to the stack storing the surviving asteroids.
- 1Asteroids moving in the same direction do not collide.
- 2Collisions only occur between a positive and a negative asteroid.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.