
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Number of Swaps 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
Advertisements