Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Asteroid Collision

Medium Acceptance 50.06% Points 30.00

You are given an array of integers, asteroids, where each element represents an asteroid. The absolute value of an element indicates the size of the asteroid, while the sign indicates its direction: positive means moving to the right, and negative means moving to the left. All asteroids move at the same speed.

When two asteroids collide:

  • The smaller asteroid is destroyed.
  • If both are the same size, they both explode.
  • Asteroids moving in the same direction will never collide.

Your task is to determine the final state of the asteroids after all collisions.

Examples
Example 1

Example 1

Input: N = 4, asteroids[] = {10, 2, -5, -10}

Output:

Explanation: Asteroid 2 and -5 collide, and -5 destroys 2. Then 10 and -5 collide, and 10 destroys -5. Finally, 10 and -10 collide, and both explode since they are the same size.

Example 2

Example 2

Input: N = 5, asteroids[] = {4, -4, 2, -2, 8}

Output: {8}

Explanation: 4 and -4 collide and both explode. 2 and -2 collide and both explode. Only 8 remains, as it moves to the right and has no collisions

Hints
Hint 1
Expected Time Complexity: O(N)
Hint 2
Expected Auxiliary Space: O(N)
Constraints
  • 1 <= N <= 10^5
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0
Companies
Amazon Microsoft Apple Visa
Topics
Stack
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions