FastPrepAsteroid Collision

Asteroid Collision

Amazon logoAmazon● MediumFULLTIMEPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

You are given an integer array asteroids representing asteroids in a row. The absolute value is an asteroid's size, and its sign is its direction: positive moves right and negative moves left. All asteroids move at the same speed.

When two asteroids moving toward each other collide, the smaller one explodes. If their sizes are equal, both explode. Asteroids moving in the same direction never collide.

Return the asteroids that remain after every collision, in their original left-to-right order.

Function

asteroidCollision(asteroids: int[]) → int[]

Examples

Example 1

asteroids = [5,10,-5]return = [5,10]

The asteroid 10 destroys -5; asteroid 5 never meets another left-moving asteroid.

Example 2

asteroids = [8,-8]return = []

The two approaching asteroids have equal size, so both explode.

Example 3

asteroids = [10,2,-5]return = [10]

Asteroid -5 first destroys 2, then asteroid 10 destroys -5.

Constraints

  • 1 <= asteroids.length <= 10^5.
  • -10^9 <= asteroids[i] <= 10^9.
  • asteroids[i] != 0.

More Amazon problems

See Amazon hiring insights
public int[] asteroidCollision(int[] asteroids) {
    // write your code here
}
asteroids[5,10,-5]
expected[5,10]
Checking account…