Program to find final states of rockets after collision in python

PythonServer Side ProgrammingProgramming

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 −

  • ls := a new list with one element nums[0]
  • for i in range 1 to size of nums - 1, do
    • if nums[i] >= 0, then
      • insert nums[i] at the end of ls
    • otherwise,
      • insert nums[i] at the end of ls
      • j := size of ls - 2
      • while j >= 0 and ls[j] >= 0, do
        • if |last element of ls| > ls[j], then
          • delete jth element from ls
        • otherwise when |last element of ls| is same as ls[j], then
          • delete jth element from ls
          • delete last element from ls
          • come out from the loop
        • otherwise,
          • delete -last element from ls
          • come out from the loop
        • j := j - 1
  • return ls

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, nums):
      ls = [nums[0]]
      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))

Input

[3, 8, 5, -5]

Output

[3, 8]
raja
Published on 02-Dec-2020 09:24:33
Advertisements