Skip to content
Decoder

Asteroid Collision

Medium

Problem

A row of asteroids is given as a list of non-zero integers. The absolute value is an asteroid's size, and the sign is its direction: positive moves right, negative moves left. All asteroids move at the same speed.

When two asteroids meet, the smaller one explodes. If they are the same size, both explode. Two asteroids moving in the same direction never meet. Return the asteroids that are left after all collisions, in order.

Example 1

Input
[5, 10, -5]
Output
[5, 10]
Why
-5 hits 10 and explodes

Example 2

Input
[8, -8]
Output
[]
Why
same size, both explode

Example 3

Input
[10, 2, -5]
Output
[10]
Why
-5 destroys 2, then 10 destroys -5

Example 4

Input
[-2, -1, 1, 2]
Output
[-2, -1, 1, 2]
Why
nobody meets

Constraints

  • 2 <= asteroids.length <= 10^4
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.