A.I, Data and Software Engineering

Asteroid Collision Solution – Leetcode coding challenge


The following asteroid collision problem is from Leetcode.

The problem

We are given an array asteroids of integers representing asteroids in a row.

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.

Example 1:

Example 2:

Example 3:

Example 4:


  • 1 <= asteroids <= 104
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0


We process from left to the right each integer value:

  • We create a list to store the result res
  • If a new asteroid value is positive, we add to the list as it will never collide with ones in res
  • Else, we remove all the positive asteroids that smaller than the new value (negative)
  • Then add the new value to res if res is empty or the last element is also negative (as it already processed in the previous run)
  • If we have two opposite asteroids of the same size, then remove the last one.

Python code for asteroid collision problem:

Java code for asteroid collision problem:

For more articles of software engineering, click here!

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest


You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.