Approach #1: Stack [Accepted]
A row of asteroids is stable if no further collisions will occur. After adding a new asteroid to the right, some more collisions may happen before it becomes stable again, and all of those collisions (if they happen) must occur right to left. This is the perfect situation for using a stack.
Say we have our answer as a stack with rightmost asteroid
top, and a
new asteroid comes in. If
new is moving right (
new > 0), or if
top is moving left (
top < 0), no collision occurs.
abs(new) < abs(top), then the
new asteroid will blow up; if
abs(new) == abs(top) then both asteroids will blow up; and if
abs(new) > abs(top), then the
top asteroid will blow up (and possibly more asteroids will, so we should continue checking.)
Time Complexity: , where is the number of asteroids. Our stack pushes and pops each asteroid at most once.
Space Complexity: , the size of
Analysis written by: @awice.