Asteroid Collision in C++


Suppose we have an array asteroids of integers representing asteroids in a row. Now for each asteroid, the absolute value represents its size, and the sign represents its direction that can be positive or negative for the right and left respectively. Each asteroid moves at the same speed.

We have to find the state of the asteroids after all collisions. When 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.

So if the input is like [5, 10, -5], then output will be [5, 10]. Here 10 and -5 collide in 10, then 5 and 10 will never collide.

To solve this, we will follow these steps −

  • Make one array ret, n := size of arr

  • for i in range 0 to n – 1

    • if ret is empty or last element of ret is positive and arr[i] is negative, then

      • insert arr[i] into ret, increase i by 1

    • otherwise

      • x := last element of ret, delete last element from ret

      • absX := |x|, absY := |arr[i]|

      • if absX = absY, then increase i by 1

      • otherwise

        • if absX > absY, then insert x into ret, increase i by 1

  • return ret

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   bool isNeg(int x){
      return x < 0;
   }
   vector<int> asteroidCollision(vector<int>& arr) {
      vector <int> ret;
      int n = arr.size();
      for(int i = 0; i< n; ){
         if(ret.empty() || !(!isNeg(ret[ret.size() - 1]) && isNeg(arr[i]))){
            ret.push_back(arr[i]);
            i++;
         } else {
            int x = ret[ret.size() - 1];
            ret.pop_back();
            int absX = abs(x);
            int absY = abs(arr[i]);
            if(absX == absY){
               i++;
            } else {
               if(absX > absY){
                  ret.push_back(x);
                  i++;
               }
            }
         }
      }
      return ret;
   }
};
main(){
   vector<int> v = {5, 10, -4};
   Solution ob;
   print_vector(ob.asteroidCollision(v));
}

Input

[5,10,-4]

Output

[5, 10, ]

Updated on: 02-May-2020

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements