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
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.
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;
}