Statementâ–¼
We are provided an array of integers, asteroids
, representing asteroids in a row. The absolute integer value of each asteroid represents its size, and the sign represents its direction. A positive sign signifies that the asteroid is moving toward the right direction, while a negative sign indicates it is moving toward the left. All asteroids move at the same speed.
We need to determine the final state of the asteroids
after all the collisions have occurred. When two asteroids of different sizes collide, the smaller one will be destroyed. If both asteroids are of the same size, both will be destroyed.
Note: Asteroids moving in the same direction will never collide.
Constraints:
2≤ asteroids.length
≤103 −103≤ asteroids[i]
≤103 asteroids[i]
î€ =0
Solution
The problem requires us to simulate the collision and find the bigger asteroids as they move along a straight path. We know that the asteroids are represented as integers in an array where:
A positive integer represents an asteroid moving to the right.
A negative integer represents an asteroid moving to the left.
The main idea is to use a stack to keep track of the asteroids still in the field. This is because we can use the stack’s properties to process all the asteroids effectively. We will go over the array of asteroids, and for each asteroid, we will compare its direction and size with the last element in the stack.
The basic algorithm to solve this problem will be:
The stack will store the asteroids that haven’t collided or have been destroyed.
We will also use a flag to check if the current asteroid should be added to the stack. Initially,
flag
value is TRUE.For each asteroid in the input list, we determine if it will collide with any asteroid already present in the stack.
If the stack isn’t empty and the top asteroid (
stack[-1]
) on the stack is moving to the right and the current asteroid is moving to the left, a collision will occur. There can be three possible outcomes:The asteroid in the stack explodes (
stack.pop()
), and we continue to check the next asteroid in the stack.Both asteroids explode, so we pop the asteroid from the stack and skip adding the current asteroid.
The current asteroid is destroyed, and we set
flag
to FALSE, preventing it from being added to the stack.
If the current asteroid survives (i.e.,
flag
remains TRUE), we add it to the stack.
After processing all the asteroids, the stack will contain them in their final state. We return the remaining stack’s contents as the final result.
Let’s look at the following illustration to get a better understanding of the algorithm: