Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Minimum Swaps To Make Identical Array

Moderate
0/80
profile
Contributed by
9 upvotes
Asked in companies
GoogleAmazonThought Works

Problem statement

You are given two arrays, ‘A’ and ‘B’, with the same elements in a different order. Your task is to make ‘B’ identical to the ‘A’ by swapping the elements in array ‘B’. You have to find out the minimum number of swaps required.

For Example:
For the first test case, ‘A’ = [5, 6, 4, 10], ‘B’ = [4, 6, 10, 5], here in the ‘B’ we can swap 4 with 10 to form [10, 6, 4, 5] and we can then swap 10 with 5 to form the array [5, 6, 4, 10] which is identical to ‘A’. Hence the answer is 2.
Detailed explanation ( Input/output format, Notes, Images )
Sample Input 1:
2
4
5 6 4 10
4 6 10 5
3
1 2 3
1 3 2
Sample Output 1:
2
1
Explanation for Sample Input 1:
For the first test case, ‘A’ = [5, 6, 4, 10], ‘B’ = [4, 6, 10, 5], here in the ‘B’ we can swap 4 with 10 to form [10, 6, 4, 5] and we can then swap 10 with 5 to form the array [5, 6, 4, 10] which is identical to ‘A’. Hence the answer is 2.

For the second test case, ‘A’ = [1, 2, 3], ‘B’ = [1, 3, 2], here in the second array we can swap 3 with 2 to form [1, 2, 3] which is identical to ‘A’. Hence the answer is 1.
Sample Input 2:
2
5
1 2 3 4 0
0 4 3 2 1
4
1 2 3 4
1 2 3 4
Sample Output 2:
2
0
Full screen
Console