Skip to content

Commit 4802f4d

Browse files
authored
Create 1722-minimize-hamming-distance-after-swap-operations.js
1 parent b0ba108 commit 4802f4d

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class UnionFind {
2+
constructor(n) {
3+
this.parents = Array(n)
4+
.fill(0)
5+
.map((e, i) => i)
6+
this.ranks = Array(n).fill(0)
7+
}
8+
root(x) {
9+
while (x !== this.parents[x]) {
10+
this.parents[x] = this.parents[this.parents[x]]
11+
x = this.parents[x]
12+
}
13+
return x
14+
}
15+
find(x) {
16+
return this.root(x)
17+
}
18+
check(x, y) {
19+
return this.root(x) === this.root(y)
20+
}
21+
union(x, y) {
22+
const [rx, ry] = [this.find(x), this.find(y)]
23+
if (this.ranks[rx] >= this.ranks[ry]) {
24+
this.parents[ry] = rx
25+
this.ranks[rx] += this.ranks[ry]
26+
} else if (this.ranks[ry] > this.ranks[rx]) {
27+
this.parents[rx] = ry
28+
this.ranks[ry] += this.ranks[rx]
29+
}
30+
}
31+
}
32+
/**
33+
* @param {number[]} source
34+
* @param {number[]} target
35+
* @param {number[][]} allowedSwaps
36+
* @return {number}
37+
*/
38+
const minimumHammingDistance = function (source, target, allowedSwaps) {
39+
let n = target.length
40+
const u = new UnionFind(n)
41+
for (let A of allowedSwaps) {
42+
let i = A[0],
43+
j = A[1]
44+
u.union(i, j)
45+
}
46+
const M = {}
47+
for (let i = 0; i < n; i++) {
48+
let j = u.find(i)
49+
if (M[j] == null) M[j] = {}
50+
if (M[j][source[i]] == null) M[j][source[i]] = 0
51+
M[j][source[i]]++
52+
}
53+
let rest = 0
54+
for (let i = 0; i < n; i++) {
55+
let j = u.find(i)
56+
if (M[j][target[i]]) {
57+
if (!--M[j][target[i]]) {
58+
delete M[j][target[i]]
59+
}
60+
} else rest++
61+
}
62+
return rest
63+
}

0 commit comments

Comments
 (0)