Asteroid Collision LeetCode
Imagine yourself observing asteroids as they travel across space, occasionally crashing into one another. A minor asteroid is destroyed when it collides with a large one. However, both asteroids are destroyed in a collision when they are the same size. Your task is to write a program that simulates these collisions and tells us which asteroids are still flying after all the collisions.
Problem statement
We are given an array asteroids of integers representing asteroids. Each asteroids[i] represents the size of the asteroid at ith position along with its direction of motion (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Our goal is to the state of the asteroids after all the collisions. If two asteroids collide, the smaller one will explode. If both asteroids are equal in size, both will explode. Two asteroids moving in the same direction will never collide.
Input- [-5, 10, -6, 20, 10, -20]- [8, -8]- [10, 2, -5]Output- [-5, 10]- []- [10]
Constraints:
asteroids.lengthasteroids[i]asteroids[i]
Example
Knowledge test
Test your knowledge of the above concept by doing the quiz below.
Choose the correct answer.
Given the array asteroids = [5, -3, 2, -4, 1], which asteroids will collide?
The asteroid at index 0 and index 1.
The asteroid at index 1 and index 3.
The asteroid at index 2 and index 4.
No asteroids will collide.
Algorithm
Let's outline the approach we'll use to solve the Asteroid Collision problem:
We'll create a
stackto store the updated state of asteroids at each iteration of theasteroidsarray.We'll start iterating over the
asteroidsarray and add the very first asteroid in this array to thestack.At each subsequent iteration of the
asteroidsarray, we’ll compare theithasteroid with the last asteroid stored in thestack. If the two asteroids are moving in the same direction, they will never collide. Hence, we’ll add theithasteroid to thestack. If the two asteroids are moving toward each other, we compare their magnitudes.If the magnitudes of the colliding asteroids are unequal, the smaller asteroid will explode. If the exploding asteroid is the one in the
stack, we simply pop it from the stack. However, if the exploding asteroid is the one in theasteroidsarray, we replace its value with 0, denoting an explosion.If the magnitudes of the colliding asteroids are equal, both will explode. We’ll pop the asteroid in the
stack, and replace the asteroid in theasteroidsarray with 0 to denote explosion.
In case of a collision, if the exploding asteroid is the one in the
stack, we need to compare the asteroid in theasteroidsarray with the next in line asteroid in thestack. The comparison will be the same as described in step 3.
The following demonstration will help you understand the algorithm better:
From the given algorithm and the demonstration, it can be observed that the collision will only occur if:
The
stackis not empty, and the last asteroid in thestackis moving toward the right (stack[-1] > 0)The asteroid in the
asteroidsarray is moving toward the left (asteroids[i] < 0)
Coding example
Now that we have an understanding of the algorithm, let’s code it.
def asteroidCollision(asteroids):stack = []for asteroid in asteroids:# Process current asteroid until no more collisionswhile stack and asteroid < 0 and stack[-1] > 0:if abs(stack[-1]) > abs(asteroid):# The current asteroid is smaller, it gets destroyedasteroid = 0elif abs(stack[-1]) < abs(asteroid):# The asteroid in the stack gets destroyedstack.pop()else:# Both asteroids are of equal size, both get destroyedstack.pop()asteroid = 0# If the current asteroid is not destroyed, add it to the stackif asteroid != 0:stack.append(asteroid)return stackprint(asteroidCollision([-5,10,-6,20,10,-20])) # output: (-5, 10)print(asteroidCollision([5,10,-5])) # output: [5, 10]print(asteroidCollision([-1, 3, 2 -3])) # output: [-1, 3]
Explanation
Let’s break down the above code:
Line 2: We create an empty array named
stack.Line 3: We iterate over the
asteroidsarray.Line 4: We create a while loop to handle multiple collisions.
Line 5: We check if a collision will occur or not based on the conditions stated earlier.
Lines 8–14: We check which of the two colliding asteroids will explode, or if both will. If it is the one in the
stack, we pop it. If, on the other hand, the exploding asteroid is the one in theasteroidsarray, we replace its value with0. If both asteroids collide, we handle both cases.Lines 15–16: If there are no more possible collisions for the given asteroid in the
asteroidsarray, we break out of the inner loop.Lines 19–20: We append the asteroid to the stack after ensuring that it did not explode (i.e., its value is not 0).
Line 23: We return the stack after all the possible collisions have occurred.
Time complexity
The time complexity of the provided code is
Space complexity
The space complexity of the code is
Free Resources