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 ; HashMap 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
def countPairs ( A , B , N , M , List ) : NEW_LINE INDENT count = 0 NEW_LINE par = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT par [ i ] = i NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT index1 = find ( par , List [ i ] [ 0 ] - 1 ) NEW_LINE index2 = find ( par , List [ i ] [ 1 ] - 1 ) NEW_LINE if ( index1 != index2 ) : NEW_LINE INDENT union ( par , index1 , index2 ) NEW_LINE DEDENT DEDENT map = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT map [ A [ i ] ] = i NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT if ( B [ i ] not in map . keys ( ) ) : NEW_LINE INDENT count += 1 NEW_LINE continue NEW_LINE DEDENT j = map [ B [ i ] ] NEW_LINE if ( find ( par , i ) != find ( par , j ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def find ( par , x ) : NEW_LINE INDENT if ( par [ x ] == x ) : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT par [ x ] = find ( par , par [ x ] ) NEW_LINE return par [ x ] NEW_LINE DEDENT DEDENT def union ( par , a , b ) : NEW_LINE INDENT a = find ( par , a ) NEW_LINE b = find ( par , b ) NEW_LINE if ( a == b ) : NEW_LINE INDENT return NEW_LINE DEDENT par [ a ] = b NEW_LINE DEDENT N = 5 NEW_LINE M = 4 NEW_LINE A = [ 1 , 5 , 9 , 2 , 3 ] NEW_LINE B = [ 2 , 4 , 5 , 1 , 3 ] NEW_LINE List = [ [ 1 , 4 ] , [ 2 , 3 ] , [ 3 , 5 ] , [ 2 , 5 ] ] NEW_LINE print ( countPairs ( A , B , N , M , List ) ) NEW_LINE