text: 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 ; 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 make 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
code: 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 ) ) ;