Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Asteroid Collision

Medium
stackarraysimulation

Asteroids move along a line: the absolute value is size, the sign is direction (positive → right, negative → left). All move at the same speed. When two collide, the smaller explodes (both if equal). Asteroids moving the same direction never meet. Return the state after all collisions.

Input: one line of space-separated non-zero integers. Output: the surviving asteroids, space-separated (empty if none survive).

Example 1
Input:
5 10 -5
Output:
5 10

10 destroys -5.

Example 2
Input:
8 -8
Output:

Mutual destruction.

Example 3
Input:
10 2 -5
Output:
10

-5 destroys 2, then 10 destroys -5.

Constraints

  • 2 ≤ asteroids.length ≤ 10^4
  • -1000 ≤ asteroids[i] ≤ 1000, non-zero.
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.