Suppose we have a list of numbers called nums and that is representing rocket's size and direction. Positive integer indicates right, and negative number represents left. And the absolute value of the number represents the rocket's size. Now when two rockets collide, the smaller one will be destroyed and the larger one will continue on its journey unchanged. When they are the same size rockets and they collide, they'll both destroy. When two rockets are moving in the same direction, they will never collide (assuming rockets speed are same). We have to find the state of the rockets after all collisions.
So, if the input is like nums = [3, 8, 5, -5], then the output will be [3, 8], as 5 and -5 will be destroyed, remaining will survive.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): ls = [nums] for i in range(1, len(nums)): if nums[i] >= 0: ls.append(nums[i]) else: ls.append(nums[i]) j = len(ls) - 2 while j >= 0 and ls[j] >= 0: if abs(ls[-1]) > ls[j]: ls.pop(j) elif abs(ls[-1]) == ls[j]: ls.pop(j) ls.pop(-1) break else: ls.pop(-1) break j -= 1 return ls ob = Solution() nums = [3, 8, 5, -5] print(ob.solve(nums))
[3, 8, 5, -5]