Python 1722.py
class Solution:
def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
result = 0
size = len(source) # == len(target)
# union-find, copied from problem 721, simplified
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
parent[find(x)] = find(y)
parent = [ i for i in range(size) ]
# merge swaps which are interconnected
for a, b in allowedSwaps:
union(a, b)
# split sequence into cycles
have = defaultdict(list)
need = defaultdict(list)
for i, (s, t) in enumerate(zip(source, target)):
cycle = find(i)
have[cycle].append(s)
need[cycle].append(t)
# process each cycle
for c in have:
freq = defaultdict(int)
for one in have[c]:
freq[one] += 1
for two in need[c]:
freq[two] -= 1
# count numbers which are present more often in "have" than in "need"
result += sum(f for f in freq.values() if f > 0)
return result
Difficulty
and has an acceptance rate of about 49% (40k+ submissions).
Typical patterns to solve this problem:
- Array
- Depth First Search
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation computes the minimum Hamming distance between two integer arrays when any number of swaps are allowed between indices that belong to the same connected component defined by allowedSwaps. It first builds disjoint sets for the indices, groups the values of source and target by their component, and then determines how many mismatched elements remain after optimal intra-component rearrangements.
Key Steps
The algorithm begins by initializing a union-find structure. The find function applies path compression, while union merges two sets by linking their roots.
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
parent[find(x)] = find(y)
All indices are initially their own parent. The loop over allowedSwaps merges each pair, creating larger connected components.
parent = [i for i in range(size)]
for a, b in allowedSwaps:
union(a, b)
Next, the code iterates over the paired elements of source and target. For each position it determines the component identifier via find(i) and appends the source value to have[cycle] and the target value to need[cycle]. The use of defaultdict(list) automatically creates a new list for each unseen component.
have = defaultdict(list)
need = defaultdict(list)
for i, (s, t) in enumerate(zip(source, target)):
cycle = find(i)
have[cycle].append(s)
need[cycle].append(t)
The core of the solution processes each component independently. A frequency map counts occurrences of values in have. The same map is decremented for each value required by need. Positive entries in the map represent surplus elements that cannot be matched within the component, and their total contributes to the final Hamming distance.
for c in have:
freq = defaultdict(int)
for one in have[c]:
freq[one] += 1
for two in need[c]:
freq[two] -= 1
result += sum(f for f in freq.values() if f > 0)
Finally, the accumulated result is returned.
Edge Cases Handled
When allowedSwaps is empty, each index forms its own component. The union-find structure leaves every parent unchanged, and the frequency comparison reduces to a direct element-wise mismatch count, correctly yielding the standard Hamming distance.
If source and target are identical, the frequency maps for each component balance to zero, and the sum of positive frequencies adds nothing to result, producing a distance of zero.
The algorithm also gracefully handles duplicate values within a component. By counting occurrences rather than relying on positional information, it correctly matches as many identical numbers as possible, leaving only the unavoidable mismatches.
Components that contain a single index are processed without special casing; the frequency map will contain one entry from have and one from need, and the positive-frequency logic still yields the correct contribution.
Large components with many repeated values are managed through the dictionary aggregation, ensuring that the net surplus is accurately captured regardless of the distribution of duplicates.
Performance Optimizations
Path compression in the find function dramatically reduces the depth of the union-find tree, making subsequent root lookups effectively constant time.
The union operation directly assigns the root of one set to the root of another without rank heuristics; however, the subsequent path compression mitigates potential imbalance.
Grouping values by component using defaultdict(list) avoids repeated scans of the arrays; each element is visited exactly once during the grouping phase.
The frequency counting step uses a single dictionary per component, incrementing for have values and decrementing for need values in two linear passes. This approach eliminates the need for separate maps or sorting, keeping the work proportional to the size of each component.
Summing only the positive frequencies avoids an explicit subtraction of matched pairs, leveraging the fact that negative entries represent excess requirements already satisfied by surplus elements.
Overall, the combination of union-find with path compression and per-component frequency aggregation yields an algorithm that scales efficiently with the number of indices and allowed swaps.
ELI5 - Simplified Explanation
Imagine there are many colorful toy blocks lined up on a shelf in a specific order. You want to make those blocks match another shelf that has a different order. You are allowed to swap the positions of certain blocks, but only if they are connected by a special rule.
Think of the blocks as groups of friends holding hands. If a block is allowed to swap with another, it is like those two blocks are part of the same team. If one block can swap with a second, and that second block can swap with a third, then all three are part of the same big team. This means any block on that team can eventually move to any of the spots held by their teammates.
To solve this, the code first finds out which blocks belong to which teams. It creates a list and writes down the name of the team leader for every single spot. Once the teams are set up, the code looks at each team one by one. It counts all the different numbers or colors that the team currently has and compares them to the numbers or colors that the team needs to occupy those same spots on the target shelf.
Because the blocks in a team can move anywhere inside their team, the code checks if there are enough of each type of block available within that group. If a team has blocks that just cannot be swapped into the right place because they are the wrong kind, those blocks count as a mistake. The code adds up all these little mistakes to see how many blocks stay in the wrong spot even after all the possible swapping is finished.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 1202: Smallest String With Swaps
- problem 2948: Make Lexicographically Smallest Array by Swapping Elements
Solved On The Same Day
- problem 3040: Maximum Number of Operations With the Same Score II
- problem 3196: Maximize Total Cost of Alternating Subarrays
- problem 3218: Minimum Cost for Cutting Cake I
- problem 3227: Vowels Game in a String
- problem 3041: Maximize Consecutive Elements in an Array After Modification
- problem 3209: Number of Subarrays With AND Value of K
- problem 3219: Minimum Cost for Cutting Cake II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality