Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 need 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] and L2 = [2, 0, 1, 3], then the output will be 2. We can swap 1 and 2 to get [0, 2, 1, 3], then swap 0 and 2 to get [2, 0, 1, 3], which matches L2.
Algorithm
To solve this, we will follow these steps ?
Initialize ans to 0
-
For each required element in L2, do ?
Find the index of this element in current L1
Remove this element from L1
Add the index to our answer
Return the total count
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))
2
How It Works
The algorithm works by simulating the process of building L2 from L1. For each element we need (from L2), we find its current position in L1. The number of swaps needed to move this element to the front equals its current index. After processing each element, we remove it from L1.
Step-by-Step Execution
def solve_with_steps(L1, L2):
L1_copy = L1.copy() # Work with a copy
ans = 0
print(f"Initial L1: {L1_copy}")
print(f"Target L2: {L2}")
for req in L2:
i = L1_copy.index(req)
print(f"Need element {req}, found at index {i}")
L1_copy.pop(i)
ans += i
print(f"After removing: {L1_copy}, swaps so far: {ans}")
return ans
L1 = [0, 1, 2, 3]
L2 = [2, 0, 1, 3]
result = solve_with_steps(L1, L2)
print(f"Total swaps needed: {result}")
Initial L1: [0, 1, 2, 3] Target L2: [2, 0, 1, 3] Need element 2, found at index 2 After removing: [0, 1, 3], swaps so far: 2 Need element 0, found at index 0 After removing: [1, 3], swaps so far: 2 Need element 1, found at index 0 After removing: [3], swaps so far: 2 Need element 3, found at index 0 After removing: [], swaps so far: 2 Total swaps needed: 2
Conclusion
This algorithm efficiently calculates the minimum adjacent swaps by tracking the position of each required element and summing up the distances. The time complexity is O(n²) due to the index search and removal operations.
