Solve Leetcode Asteroid Collision in Python

Whats the problem asking?

Imagine a row of asteroids, each moving in a set direction, either left or right, at a fixed speed. Each asteroid’s size is given as an integer value, and its direction of movement is indicated by the sign of the integer; positive for rightward and negative for leftward.

In this scenario, whenever two asteroids, moving towards each other, meet, they collide. The result of a collision depends on the sizes of the two asteroids. If one asteroid is larger, the smaller one will explode and disappear. If both asteroids are the same size, they both explode and vanish. Importantly, two asteroids moving in the same direction will never collide.

The problem asks for the final state of the asteroid field after all possible collisions have occurred.

Approach:

The key to solving this problem lies in understanding the conditions under which collisions can happen. Two asteroids moving in the same direction will never collide, even if they are next to each other. However, an asteroid moving to the right can crash into an asteroid moving to the left, if the right-moving asteroid is on the left of the left-moving asteroid.

So, how do we keep track of this? We start from the leftmost side of the asteroid field and go through each asteroid one by one. For each asteroid moving to the left, we check if it collides with any asteroid before it that’s moving to the right. We keep repeating this until the asteroid has either exploded or there are no more asteroids moving to the right in front of it. To achieve this, we use a programming concept called a ‘stack’.

A stack is a data structure that follows a ‘last in, first out’ (LIFO) principle, similar to a stack of plates. You can only take from or add to the top of the stack.

In our solution, we use a stack to keep track of the asteroids we’ve encountered so far. If an asteroid can continue moving without colliding with any others, we add it to the top of our stack. If an asteroid would collide with others, we compare their sizes to see which one explodes.

Solution code with line by line explanation:

# We start by setting up an empty stack.
stack = []

# We then go through each asteroid in the array.
for ast in asteroids:
    # A collision only happens if:
    # There are asteroids in our stack, the current asteroid (ast) is moving left (negative), and the asteroid at the top of the stack is moving right (positive).
    while stack and ast < 0 and stack[-1] > 0:
        # We calculate the result of a collision by comparing the sizes of the two asteroids.
        diff = ast + stack[-1]
        # If the asteroid we're checking (ast) is larger, the smaller one (on the top of the stack) explodes and is removed from the stack.
        if diff < 0:
            stack.pop()
        # If the asteroid we're checking (ast) is smaller or the same size, it will explode and we stop checking for more collisions.
        elif diff >= 0:
            ast = 0
            if diff == 0:
                stack.pop()
    # If the asteroid (ast) still exists after checking for collisions, we add it to the top of our stack.
    if ast:
        stack.append(ast)
        
# Finally, we return the state of the stack, which represents the final state of the asteroid field.
return stack 

Solution code only:

stack = []

for ast in asteroids:
    while stack and ast < 0 and stack[-1] > 0:
        diff = ast + stack[-1]
        if diff < 0:
            stack.pop()
        elif diff >= 0:
            ast = 0
            if diff == 0:
                stack.pop()
    if ast:
        stack.append(ast)
        
return stackComplexity analysis:

Time Complexity: O(N). We only go through the array once, and for each asteroid, we perform operations a maximum of two times: when we first encounter it, and potentially when removing it from the stack.

Space Complexity: O(N). We only need space for the stack; the maximum number of asteroids that could be in the stack is equal to the total number of asteroids if no collisions occur. The final list we return is used to store the output, which doesn’t count towards the space complexity.

 

If you found this article useful, consider following me for more just like this one. Your thoughts and feedback are important to me, and I welcome any suggestions for future topics you’d like to see covered. To make sharing your ideas with me even easier, I’ve created a quick feedback form which you can access here. Your input is greatly appreciated! Don’t hesitate to reach out — your engagement is what makes this community thrive.

Thanks for reading and happy coding! :)


#python 

Solve Leetcode Asteroid Collision in Python
1.00 GEEK