Minimize count of unequal elements at corresponding indices between given arrays | Function that count of the mismatched pairs in bot the array ; Create a parent array and initialize it ; Preprocessing of the given pairs of indices ; 1 - based indexing ; If both indices doesn 't belong  to same component ; Insert the indices in same component ; Map to get the indices of array A ; If current element is not present in array B then count this as mismatched ; Get the index of the element in array B ; Check if both indices belong to same connected component if not increment the count ; Return answer ; Function that gives the connected component of each index ; Function that creates the connected components ; Find parent of a and b recursively ; Update the parent of a ; Driver Code ; Given arrays A [ ] , B [ ] ; List of indices ; Function call
function countPairs ( A , B , N , M , List ) { var count = 0 ; var par = Array ( N + 1 ) ; for ( var i = 0 ; i <= N ; i ++ ) par [ i ] = i ; for ( var i = 0 ; i < M ; i ++ ) { var index1 = find ( par , List [ i ] [ 0 ] - 1 ) ; var index2 = find ( par , List [ i ] [ 1 ] - 1 ) ; if ( index1 != index2 ) { unionn ( par , index1 , index2 ) ; } } var mp = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { mp . set ( A [ i ] , i ) ; } for ( var i = 0 ; i < N ; i ++ ) { if ( A [ i ] != B [ i ] ) { if ( ! mp . has ( B [ i ] ) ) { count ++ ; continue ; } var j = mp . get ( B [ i ] ) ; if ( find ( par , i ) != find ( par , j ) ) count ++ ; } } return count ; } function find ( par , x ) { if ( par [ x ] == x ) return x ; else return par [ x ] = find ( par , par [ x ] ) ; } function unionn ( par , a , b ) { a = find ( par , a ) ; b = find ( par , b ) ; if ( a == b ) return ; par [ a ] = b ; } var N = 5 ; var M = 4 ; var A = [ 1 , 5 , 9 , 2 , 3 ] ; var B = [ 2 , 4 , 5 , 1 , 3 ] ; var List = [ [ 1 , 4 ] , [ 2 , 3 ] , [ 3 , 5 ] , [ 2 , 5 ] ] ; document . write ( countPairs ( A , B , N , M , List ) ) ;