Problem · Array

Asteroid Collision

Learn this problem
MediumAdobe logoAdobeFULLTIMEONSITE INTERVIEW

Problem statement

An array describes asteroids in a row. The absolute value of each integer is the asteroid's size, while its sign gives its direction: positive moves right and negative moves left. All asteroids move at the same speed.

When two asteroids meet, the smaller one is destroyed. If they have equal size, both are destroyed. Asteroids moving in the same direction never meet.

Return the surviving asteroids in their original order.

Function

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

Examples

Example 1

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

The asteroid of size 10 destroys the left-moving asteroid of size 5.

Example 2

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

The two asteroids have equal size, so both disappear.

Example 3

asteroids = [-2,-1,1,2]return = [-2,-1,1,2]

No right-moving asteroid appears to the left of a left-moving asteroid, so no collision occurs.

Constraints

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

More Adobe problems

drafts saved locally
public int[] asteroidCollision(int[] asteroids) {
    // Write your solution here.
}
asteroids[5,10,-5]
expected[5,10]
checking account