Stacks and Queues Matching and cancelling
197. Asteroid Collision
You are given an array of integers asteroids that describes a row of asteroids, listed from left to right.
The absolute value of each number is the asteroid's size, and its sign is its direction: a positive asteroid
moves right and a negative one moves left. All asteroids move at the same speed.
Two asteroids meet only when one moving right is somewhere to the left of one moving left. When they meet, the smaller one explodes and the larger one carries on with its size unchanged. If they are the same size, both explode. Asteroids moving the same way never meet, and neither do a left-mover and a right-mover that are flying apart.
Return the asteroids that are left once no more collisions can happen, in their order from left to right. If
none are left, return an empty array, [].
Example 1
Input: asteroids = [4, 7, -5, 2, -2, -8, 3]
[-8,3]Explanation: -5 hits 7 and explodes. 2 and -2 are the same size, so both explode. -8 then destroys 7 and
4 and flies off to the left. 3 moves right with nothing ahead of it.
Example 2
Input: asteroids = [-6, -1, 5, 9]
[-6,-1,5,9]Explanation: The left-movers are all on the left and the right-movers on the right. They fly apart, so nothing ever collides.
Example 3
Input: asteroids = [6, 2, -6]
[]Explanation: -6 destroys 2 and then meets 6. They are the same size, so both explode, and no asteroid is left.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ asteroids.length ≤ 105-109 ≤ asteroids[i] ≤ 109, andasteroids[i] ≠ 0
Clarifying questions
What you would ask an interviewer before writing any code.