Program to check if we reverse sublist of one list to form second list or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists of numbers called A, and B. We have to take some sublist in A and reverse it. Then check whether it is possible to turn A into B or not. We can take sublist and reverse it any number of times.

So, if the input is like A = [2, 3, 4, 9, 10], B = [4, 3, 2, 10, 9], then the output will be True as we can reverse [2,3,4] and [9,10].

To solve this, we will follow these steps −

  • res := a map, initially empty
  • for each n in nums, do
    • res[n] := res[n] + 1
  • for each t in target, do
    • res[t] := res[t] - 1
  • return true when all elements in the values of res is same as 0.

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import defaultdict
class Solution:
   def solve(self, nums, target):
      res = defaultdict(int)
      for n in nums:
         res[n] += 1
      for t in target:
         res[t] -= 1
      return all(n == 0 for n in res.values())
ob = Solution()
A = [2, 3, 4, 9, 10]
B = [4, 3, 2, 10, 9]
print(ob.solve(A, B))

Input

[2, 3, 4, 9, 10], [4, 3, 2, 10, 9]

Output

True
raja
Published on 07-Oct-2020 13:40:31
Advertisements