Given two arrays that have the same values but in a different order and having no duplicate elements in it, we need to make a second array the same as a first array using the minimum number of swaps.
Examples:
Input : arrA[] = {3, 6, 4, 8},
arrB[] = {4, 6, 8, 3}
Output : 2
Explanation: we can make arrB to same as arrA in 2 swaps which are shown below, swap 4 with 8,
arrB = {8, 6, 4, 3} swap 8 with 3, arrB = {3, 6, 4, 8}
This problem can be solved by modifying the array B. We save the index of array A elements in array B i.e. if ith element of array A is at jth position in array B, then we will make arrB[i] = j
For above given example, modified array B will be, arrB = {3, 1, 0, 2}. This modified array represents the distribution of array A element in array B and our goal is to sort this modified array in a minimum number of swaps because after sorting only array B element will be aligned with array A elements.
Now count of minimum swaps for sorting an array can be found by visualizing the problem as a graph, this problem is already explained in previous article.
So we count these swaps in a modified array and that will be our final answer.
Please see the below code for a better understanding.
C++
#include <bits/stdc++.h>
using namespace std;
int minSwapsToSort(int arr[], int n)
{
pair<int, int> arrPos[n];
for (int i = 0; i < n; i++)
{
arrPos[i].first = arr[i];
arrPos[i].second = i;
}
sort(arrPos, arrPos + n);
vector<bool> vis(n, false);
int ans = 0;
for (int i = 0; i < n; i++)
{
if (vis[i] || arrPos[i].second == i)
continue;
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = 1;
j = arrPos[j].second;
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
int minSwapToMakeArraySame(int a[], int b[], int n)
{
map<int, int> mp;
for (int i = 0; i < n; i++)
mp[b[i]] = i;
for (int i = 0; i < n; i++)
b[i] = mp[a[i]];
return minSwapsToSort(b, n);
}
int main()
{
int a[] = {3, 6, 4, 8};
int b[] = {4, 6, 8, 3};
int n = sizeof(a) / sizeof(int);
cout << minSwapToMakeArraySame(a, b, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int minSwapsToSort(int arr[], int n)
{
ArrayList<ArrayList<Integer>> arrPos = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < n; i++)
{
arrPos.add(new ArrayList<Integer>(Arrays.asList(arr[i],i)));
}
Collections.sort(arrPos, new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
return o1.get(0).compareTo(o2.get(0));
}
});
boolean[] vis = new boolean[n];
int ans = 0;
for (int i = 0; i < n; i++)
{
if (vis[i] || arrPos.get(i).get(1) == i)
continue;
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = true;
j = arrPos.get(j).get(1);
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
static int minSwapToMakeArraySame(int a[], int b[], int n)
{
Map<Integer, Integer> mp
= new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++)
{
mp.put(b[i], i);
}
for (int i = 0; i < n; i++)
b[i] = mp.get(a[i]);
return minSwapsToSort(b, n);
}
public static void main (String[] args)
{
int a[] = {3, 6, 4, 8};
int b[] = {4, 6, 8, 3};
int n = a.length;
System.out.println( minSwapToMakeArraySame(a, b, n));
}
}
|
Python3
def minSwapsToSort(arr, n):
arrPos = [[0 for x in range(2)]
for y in range(n)]
for i in range(n):
arrPos[i][0] = arr[i]
arrPos[i][1] = i
arrPos.sort()
vis = [False] * (n)
ans = 0
for i in range(n):
if (vis[i] or arrPos[i][1] == i):
continue
cycle_size = 0
j = i
while (not vis[j]):
vis[j] = 1
j = arrPos[j][1]
cycle_size+= 1
ans += (cycle_size - 1)
return ans
def minSwapToMakeArraySame(a, b, n):
mp = {}
for i in range(n):
mp[b[i]] = i
for i in range(n):
b[i] = mp[a[i]]
return minSwapsToSort(b, n)
if __name__ == "__main__":
a = [3, 6, 4, 8]
b = [4, 6, 8, 3]
n = len(a)
print(minSwapToMakeArraySame(a, b, n))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG{
static int minSwapsToSort(int[] arr, int n)
{
List<List<int>> arrPos = new List<List<int>>();
for (int i = 0; i < n; i++)
{
arrPos.Add(new List<int>(){arr[i],i});
}
arrPos=arrPos.OrderBy(x => x[0]).ToList();
bool[] vis = new bool[n];
Array.Fill(vis,false);
int ans = 0;
for (int i = 0; i < n; i++)
{
if (vis[i] || arrPos[i][1] == i)
continue;
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = true;
j = arrPos[j][1];
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
static int minSwapToMakeArraySame(int[] a, int[] b, int n)
{
Dictionary<int,int> mp = new Dictionary<int,int>();
for (int i = 0; i < n; i++)
{
mp.Add(b[i],i);
}
for (int i = 0; i < n; i++)
{
b[i] = mp[a[i]];
}
return minSwapsToSort(b, n);
}
static public void Main (){
int[] a = {3, 6, 4, 8};
int[] b = {4, 6, 8, 3};
int n = a.Length;
Console.WriteLine( minSwapToMakeArraySame(a, b, n));
}
}
|
Javascript
<script>
function minSwapsToSort(arr,n)
{
let arrPos = [];
for (let i = 0; i < n; i++)
{
arrPos.push([arr[i],i]);
}
arrPos.sort(function(a,b){return a[0]-b[0];});
let vis = new Array(n);
for(let i=0;i<n;i++)
{
vis[i]=false;
}
let ans = 0;
for (let i = 0; i < n; i++)
{
if (vis[i] || arrPos[i][1] == i)
continue;
let cycle_size = 0;
let j = i;
while (!vis[j])
{
vis[j] = true;
j = arrPos[j][1];
cycle_size++;
}
ans += (cycle_size - 1);
}
return ans;
}
function minSwapToMakeArraySame(a,b,n)
{
let mp = new Map();
for (let i = 0; i < n; i++)
{
mp.set(b[i], i);
}
for (let i = 0; i < n; i++)
b[i] = mp.get(a[i]);
return minSwapsToSort(b, n);
}
let a=[3, 6, 4, 8];
let b=[4, 6, 8, 3];
let n = a.length;
document.write( minSwapToMakeArraySame(a, b, n));
</script>
|
Output:
2
Time Complexity: O(n log n)
Auxiliary Space: O(n)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.