AlgoLounge

Asteroid Collision

medium

Leetcode 735. Asteroid Collision

You are given an array asteroids of integers representing asteroids in a row. The indices of the asteroid in the array represent their relative position in space.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Examples

Example 1

Input:  asteroids = [2,4,-4,-1]
Output: [2]

Example 2

Input:  asteroids = [5,5]
Output: [5,5]

Example 3

Input:  asteroids = [7,-3,9]
Output: [7,9]

Constraints

  • 2 <= asteroids.length <= 10,000
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0
TypeScript
Loading editor…
List of test cases (13)
Case 1
asteroids = [2,4,-4,-1]
Case 2
asteroids = [5,5]
Case 3
asteroids = [7,-3,9]
Case 4
asteroids = [-2,-1,1,2]
Case 5
asteroids = [10,2,-5]
Case 6
asteroids = [8,-8]
Case 7
asteroids = [-2,-2,1,-2]
Case 8
asteroids = [1,-1,-2,-2]
Case 9
asteroids = [3,5,-3,-5,-6]
Case 10
asteroids = [1,2,3,4,5]
Case 11
asteroids = [-5,-4,-3,-2,-1]
Case 12
asteroids = [-1000,1000,-1000]
Case 13
asteroids = [5,-3,10,-20]