Asteroid Collision
You are given an array/list “ASTEROIDS” representing asteroids in a row. For each element of the given array, its absolute value denotes the size of that asteroid and its sign denotes the direction it is moving in(+ve meaning right and -ve meaning left). An asteroid with a weight of 0 denotes a massless asteroid that moves in the right direction.
All asteroids are moving at the same speed. Whenever two asteroids collide, the smaller asteroid gets destroyed. If both the asteroids have the same size, then both the asteroids get destroyed. Two asteroids moving in the same direction never collide.
You are supposed to find the state of the asteroids after all collisions.
For Example :
ASTEROIDS = {3,-2,4}
The first asteroid will destroy the second asteroid. Hence, after the collision, the state of the asteroids will be {3,4}.
Input Format :
The first line contains a single integer ‘T’ denoting the number of test cases. The test cases are as follows.
The first line of each test case contains a single integer ‘N’ denoting the number of elements in the array/list.
The second line of each test case contains ‘N’ single space-separated integers denoting the elements of the array/list.
Output Format :
For each test case, print all remaining asteroids separated by a single space.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 50
1 <= 'N' <= 10^4
-10^5 <= ASTEROIDS[i] <= 10^5
Where ASTEROIDS[i] denotes the i-th asteroid.
Time Limit: 1 sec
CodingNinjas
author
2y
Thought about stack solution.
CodingNinjas
author
2y
Stack Based Approach
The idea is to use the stack to maintain the state of the asteroids. If we find an asteroid moving to the left (-ve value), let’s say at index i, then it will collide with an aster...read more
Help your peers!
Add answer anonymously...
Top Quizizz Senior Software Engineer interview questions & answers
Popular interview questions of Senior Software Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app