1722. Minimize Hamming Distance After Swap Operations

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1722

class Solution:
    def minimumHammingDistance(
        self, source: List[int], target: List[int], allowedSwaps: List[List[int]]
    ) -> int:
        def find(x: int) -> int:
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        n = len(source)
        p = list(range(n))
        for a, b in allowedSwaps:
            p[find(a)] = find(b)
        cnt = defaultdict(Counter)
        for i, x in enumerate(source):
            j = find(i)
            cnt[j][x] += 1
        res = 0
        for i, x in enumerate(target):
            j = find(i)
            cnt[j][x] -= 1
            res += cnt[j][x] < 0
        return res