v9.1.1
Menu

Asteroid Collision

mediumPROStacks & QueuesMicrosoft DSA

Given an array of integers representing asteroids moving in a row. Positive = right, negative = left. Equal size = both destroyed. Bigger one survives.

Return the state after all collisions. Output space-separated.

Example

Input
5,10,-5
Output
5 10
Reasoning
  • We start with the input array: 5, 10, -5, representing asteroids moving to the right (5, 10) and left (-5).
  • The asteroid -5 (moving left) collides with 5 (moving right). Since they are of equal size (∣5∣=∣−5∣|5| = |-5|), both are destroyed.
  • The remaining asteroid 10 (moving right) has no other asteroids to collide with, so it remains in the output.
  • The final output is the state after all collisions: 5 is destroyed, and 10 remains, resulting in the output: 5 10

Constraints

  • 2 <= len(asteroids) <= 10^4
  • -1000 <= asteroids[i] <= 1000, != 0

More from Microsoft DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.