oneby7

Stacks and Queues Matching and cancelling

197. Asteroid Collision

Medium

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]

Output: [-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]

Output: [-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]

Output: []

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.

asteroids = [2, -4, 4, -2]

Constraints

  • 1 ≤ asteroids.length ≤ 105
  • -109 ≤ asteroids[i] ≤ 109, and asteroids[i] ≠ 0

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.