Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

Asteroids that collide in a row

Medium · Target 15 minutes · Stack· Type asked at

You're given an array asteroids of non-zero integers, all in a row. The absolute value is an asteroid's size and the sign is its direction (positive moves right, negative moves left), and they all move at the same speed. When two meet the smaller one explodes, and if they're the same size both do. Asteroids moving the same way never meet. Return the asteroids that are left once nothing more can collide, in their original order.

Examples

InputOutputWhy
asteroids = [5, 10, -5][5, 10]The −5 hits the 10 and it's the −5 that explodes.
asteroids = [8, -8][]They're the same size so both of them go.
asteroids = [10, 2, -5][10]The −5 destroys the 2 and then the 10 destroys the −5.
asteroids = [-2, -1, 1, 2][-2, -1, 1, 2]The two on the left are moving away from the two on the right, so nothing ever meets.

Constraints

  • 1 ≤ n ≤ 10⁴
  • −1000 ≤ asteroids[i] ≤ 1000
  • asteroids[i] ≠ 0

Hints

Hint 1

It's only a right-mover with a left-mover somewhere after it that can collide, so which right-mover do you think a new left-mover hits first?

Hint 2

It's the nearest one before it that's still there, which is the last right-mover you've kept, and I'd say that sounds a lot like the top of a stack.

Hint 3

So you'd push right-movers, and for a left-mover you pop the smaller right-movers off the top until it either dies against a bigger one or takes an equal one with it (or survives, in which case it's pushed).

Where people lose marks

  • Letting a left-mover collide with a left-mover that's on the stack, when two asteroids going the same way never meet and the loop should only pop right-movers.
  • Forgetting about the equal case, where the left-mover and the top both explode and you mustn't push the left-mover afterwards.
  • Treating [−2, 2] as a collision. I'd draw it out, because the negative one's heading left and away from the other, and it's only a positive followed by a negative that can meet.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.