- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

- Related Articles
- Program to find number of steps required to change one word to another in Python
- Program to count number of swaps required to group all 1s together in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to find number of swaps required to sort the sequence in python
- Program to find minimum number of operations required to make one number to another in Python
- Program to find minimum swaps required to make given anagram in python
- Program to count number of operations required to all cells into same color in Python
- Program to count minimum number of operations required to make numbers non coprime in Python?
- Program to count number of operations required to convert all values into same in Python?
- Program to count number of flipping required to make all x before y in Python
- Program to count number of 5-star reviews required to reach threshold percentage in Python
- Minimum number of swaps required to sort an array in C++
- Python program to get the indices of each element of one list in another list
- Program to count number of walls required to partition top-left and bottom-right cells in Python
- Java Program to copy value from one list to another list

Advertisements