735. Asteroid Collision

735. Asteroid Collision

[Medium] “For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode."

Link to Leetcode

Note: old solution, should review (TODO:)

Python3:

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        
        stack = []
        
        # reduce any pair of positive then negative
        for asteroid in asteroids:
            while stack and stack[-1] > 0 and asteroid < 0:
                if abs(stack[-1]) > abs(asteroid):
                    # destroy right asteroid
                    break
                elif abs(stack[-1]) == abs(asteroid):
                    # destroy left and right asteroid
                    stack.pop()
                    break
                elif abs(asteroid) > abs(stack[-1]):
                    # destroy left asteroid
                    stack.pop()
                    # continue
            else:
                stack.append(asteroid)
    
        return stack