Google Online Assessment Question 2021 || Velocity of 2 balls
4323

I recently gave this google online challenge on 10th of July 2021 for intern roles

We were given 2 questions and I could not solve both ( although I was partially able to solve the second question) which I'll be discussing here

The second question was :

You are given 'n' balls and they move i either right or left direction and for balls moving in opposite direction, collision takes place and the one with less velocity(magnitude) gets destroyed

I dont remember the constraints but I am damn sure :
The question is exactly similar to Astroid Collision Problem on leetcode

Question:

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:

Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.

Example 2:

Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.

Some key points

  • Positive magnitude means right direction and negative magnitude means left direction
  • one by one consider all elements and if they are of the same direction , great ! include them else compare whose magnitude is bigger and the one with less magnitude gets destroyed
  • that's it ! I coud not think of this approach/logic in the actual round but was able to do it after the competition :'(
  • Since we need to modify the previous element as well as compare current , "stack" would be the best data structure here ( although it can also be done using vector)

image

Code:

 vector<int> asteroidCollision(vector<int>& asteroids) {
        vector<int> ans;
        stack<int> st;
        
        for(auto ast : asteroids)
        {
            if(ast>0) st.push(ast);
                     
            else {                 
                
                    while(!st.empty() && st.top()>0 && st.top()<abs(ast)) st.pop();
                
                    if(st.empty() || st.top()<0) st.push(ast);  
                    else if(st.top() + ast==0) st.pop();   
                }
            }       
        
        while(!st.empty())
        {
            ans.push_back(st.top());
            st.pop();
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
Comments (2)