Program to count number of swaps required to change one list to another in Python?

PythonServer Side ProgrammingProgramming

Suppose we have two lists of numbers L1 and L2, the length of each list is n and each value is unique to its list, and values are in range 1 to n, we have to find the minimum number of adjacent swaps required to transform L1 to L2.

So, if the input is like L1 = [0, 1, 2, 3] L2 = [2, 0, 1, 3], then the output will be 2, as we can swap 1 and 2, L1 will be [0, 2, 1, 3], and then 0 and 2, L1 will be [2, 0, 1, 3], this is same as L2.

To solve this, we will follow these steps:

  • ans := 0

  • for each req in L2, do

    • i := index of req in L1

    • delete ith element from L1

    • ans := ans + i

  • return ans

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, L1, L2):
      ans = 0
      for req in L2:
         i = L1.index(req)
         L1.pop(i)
         ans += i
      return ans

ob = Solution()
L1 = [0, 1, 2, 3]
L2 = [2, 0, 1, 3]
print(ob.solve(L1, L2))

Input

[0, 1, 2, 3],[2, 0, 1, 3]

Output

2
raja
Published on 10-Nov-2020 08:07:36
Advertisements