Minimum swaps to make two arrays identical | Function returns the minimum number of swaps required to sort the array This method is taken from below post https : www . geeksforgeeks . org / minimum - number - swaps - required - sort - array / ; Create an array of pairs where first element is array element and second element is position of first element ; Sort the array by array element values to get right position of every element as second element of pair . ; To keep track of visited elements . Initialize all elements as not visited or false . ; Initialize result ; Traverse array elements ; Already swapped and corrected or already present at correct pos ; Find out the number of node in this cycle and add in ans ; Move to next node ; Update answer by adding current cycle . ; Return result ; Method returns minimum number of swap to mak array B same as array A ; map to store position of elements in array B we basically store element to index mapping . ; now we 're storing position  of array A elements  in array B. ; Returing minimum swap for sorting in modified array B as final answer ; Driver code
def minSwapsToSort ( arr , n ) : NEW_LINE INDENT arrPos = [ [ 0 for x in range ( 2 ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arrPos [ i ] [ 0 ] = arr [ i ] NEW_LINE arrPos [ i ] [ 1 ] = i NEW_LINE DEDENT arrPos . sort ( ) NEW_LINE vis = [ False ] * ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] or arrPos [ i ] [ 1 ] == i ) : NEW_LINE INDENT continue NEW_LINE DEDENT cycle_size = 0 NEW_LINE j = i NEW_LINE while ( not vis [ j ] ) : NEW_LINE INDENT vis [ j ] = 1 NEW_LINE j = arrPos [ j ] [ 1 ] NEW_LINE cycle_size += 1 NEW_LINE DEDENT ans += ( cycle_size - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def minSwapToMakeArraySame ( a , b , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ b [ i ] ] = i NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT b [ i ] = mp [ a [ i ] ] NEW_LINE DEDENT return minSwapsToSort ( b , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 6 , 4 , 8 ] NEW_LINE b = [ 4 , 6 , 8 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( minSwapToMakeArraySame ( a , b , n ) ) NEW_LINE DEDENT