Problem: Minimize Hamming Distance After Swap Operations

You are given two integer arrays, `source` and `target`, both of length `n`.
You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai,
bi]` indicates that you are allowed to swap the elements at index `ai` and
index `bi` (0-indexed) of array `source`. Note that you can swap elements at a
specific pair of indices multiple times and in any order.

The Hamming distance of two arrays of the same length, `source` and `target`,
is the number of positions where the elements are different. Formally, it is
the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]`
(0-indexed).

Return the minimum Hamming distance of `source` and `target` after performing
any amount of swap operations on array `source`.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class UnionFind:
  def __init__(self, n: int):
    self.id = list(range(n))
    self.rank = [0] * n

  def unionByRank(self, u: int, v: int) -> None:
    i = self.find(u)
    j = self.find(v)
    if i == j:
      return
    if self.rank[i] < self.rank[j]:
      self.id[i] = j
    elif self.rank[i] > self.rank[j]:
      self.id[j] = i
    else:
      self.id[i] = j
      self.rank[j] += 1

  def find(self, u: int) -> int:
    if self.id[u] != u:
      self.id[u] = self.find(self.id[u])
    return self.id[u]


class Solution:
  def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
    n = len(source)
    ans = 0
    uf = UnionFind(n)
    groupIdToCount = [collections.Counter() for _ in range(n)]

    for a, b in allowedSwaps:
      uf.unionByRank(a, b)

    for i in range(n):
      groupIdToCount[uf.find(i)][source[i]] += 1

    for i in range(n):
      groupId = uf.find(i)
      count = groupIdToCount[groupId]
      if target[i] not in count:
        ans += 1
      else:
        count[target[i]] -= 1
        if count[target[i]] == 0:
          del count[target[i]]

    return ans


Java solution:
class UnionFind {
  public UnionFind(int n) {
    id = new int[n];
    rank = new int[n];
    for (int i = 0; i < n; ++i)
      id[i] = i;
  }

  public void unionByRank(int u, int v) {
    final int i = find(u);
    final int j = find(v);
    if (i == j)
      return;
    if (rank[i] < rank[j]) {
      id[i] = j;
    } else if (rank[i] > rank[j]) {
      id[j] = i;
    } else {
      id[i] = j;
      ++rank[j];
    }
  }

  public int find(int u) {
    return id[u] == u ? u : (id[u] = find(id[u]));
  }

  private int[] id;
  private int[] rank;
}

class Solution {
  public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {
    final int n = source.length;
    int ans = 0;
    UnionFind uf = new UnionFind(n);
    Map<Integer, Integer>[] groupIdToCount = new Map[n];

    for (int i = 0; i < n; ++i)
      groupIdToCount[i] = new HashMap<>();

    for (int[] allowedSwap : allowedSwaps) {
      final int a = allowedSwap[0];
      final int b = allowedSwap[1];
      uf.unionByRank(a, b);
    }

    for (int i = 0; i < n; ++i)
      groupIdToCount[uf.find(i)].merge(source[i], 1, Integer::sum);

    for (int i = 0; i < n; ++i) {
      final int groupId = uf.find(i);
      Map<Integer, Integer> count = groupIdToCount[groupId];
      if (!count.containsKey(target[i]))
        ++ans;
      else if (count.merge(target[i], -1, Integer::sum) == 0)
        count.remove(target[i]);
    }

    return ans;
  }
}


C++ solution:
class UnionFind {
 public:
  UnionFind(int n) : id(n), rank(n) {
    iota(id.begin(), id.end(), 0);
  }

  void unionByRank(int u, int v) {
    const int i = find(u);
    const int j = find(v);
    if (i == j)
      return;
    if (rank[i] < rank[j]) {
      id[i] = j;
    } else if (rank[i] > rank[j]) {
      id[j] = i;
    } else {
      id[i] = j;
      ++rank[j];
    }
  }

  int find(int u) {
    return id[u] == u ? u : id[u] = find(id[u]);
  }

 private:
  vector<int> id;
  vector<int> rank;
};

class Solution {
 public:
  int minimumHammingDistance(vector<int>& source, vector<int>& target,
                             vector<vector<int>>& allowedSwaps) {
    const int n = source.size();
    int ans = 0;
    UnionFind uf(n);
    vector<unordered_map<int, int>> groupIdToCount(n);

    for (const vector<int>& allowedSwap : allowedSwaps) {
      const int a = allowedSwap[0];
      const int b = allowedSwap[1];
      uf.unionByRank(a, b);
    }

    for (int i = 0; i < n; ++i)
      ++groupIdToCount[uf.find(i)][source[i]];

    for (int i = 0; i < n; ++i) {
      const int groupId = uf.find(i);
      unordered_map<int, int>& count = groupIdToCount[groupId];
      if (!count.contains(target[i]))
        ++ans;
      else if (--count[target[i]] == 0)
        count.erase(target[i]);
    }

    return ans;
  }
};