What is Asteroid Collision
Asteroids move in a line. A positive value moves right, a negative value moves left. Two asteroids collide only when a right-mover is already on the stack and a left-mover arrives.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each asteroid is pushed and popped at most once. |
| Space | O(n) | No collisions means every asteroid stays. |
Implementation
def solve(self, nums):
st = []
for x in nums:
alive = True
while alive and st and st[-1] > 0 and x < 0:
if st[-1] < -x: st.pop()
elif st[-1] == -x:
st.pop(); alive = False
else:
alive = False
if alive: st.append(x)
return st