Minimize Hamming Distance After Swap Operations

Problem Description

Ah, the classic Hamming distance problem! Imagine you and your friend are trying to arrange a party, but you both have different ideas about the guest list. You want to invite your favorite people, while your friend insists on bringing their own crew. The result? A chaotic mix of guests that leads to awkward conversations and a lot of eye-rolling.

In the world of coding, this is akin to the “Minimize Hamming Distance After Swap Operations” problem. You have two lists: a source list and a target list. Your goal is to make the source list look as much like the target list as possible by swapping elements, but only those that are allowed. Think of it as trying to rearrange your party guests to minimize the number of awkward encounters!

Code Solution


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

Approach Explanation

The solution employs a Union-Find data structure to group indices of the source list that can be swapped. By uniting the indices based on allowed swaps, we can then count how many elements in each group match the target list. The final step is to calculate the Hamming distance by checking how many elements in the target list cannot be matched with the source list.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n + m)
Space Complexity O(n)

Real-World Example

Imagine you’re at a buffet with a variety of dishes, but you and your friends have different tastes. You want to swap your broccoli for their mac and cheese. The goal is to minimize the number of dishes you dislike on your plate. Similarly, in this problem, you want to minimize the number of mismatches between your source list and the target list by swapping elements based on allowed operations.

Similar Problems

If you enjoyed this problem, you might also like these: