Skip to content

Commit edacbb9

Browse files
committed
add optimal solution for union find question
1 parent 37fe532 commit edacbb9

File tree

1 file changed

+47
-5
lines changed

1 file changed

+47
-5
lines changed

famous-algorithms/union-find.js

+47-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
// Do not edit the class below except for
2-
// the constructor and the createSet, find,
3-
// and union methods. Feel free to add new
4-
// properties and methods to the class.
5-
61
class UnionFind {
72
constructor() {
83
this.parents = {};
@@ -38,3 +33,50 @@ class UnionFind {
3833
}
3934
}
4035
}
36+
37+
//
38+
// SOLUTION 2
39+
// OPTIMAL SOLUTION
40+
//
41+
class UnionFind {
42+
constructor() {
43+
this.parents = {};
44+
this.ranks = {};
45+
}
46+
47+
createSet(value) {
48+
this.parents[value] = value;
49+
this.ranks[value] = 0;
50+
}
51+
52+
// O(alpha(n)), approximately O(1) time and space
53+
// where n is the total numbe of values
54+
find(value) {
55+
if (!(value in this.parents)) return null;
56+
57+
// if the parent is different to the value
58+
// find parent calling find recursively
59+
if (value !== this.parents[value]) {
60+
this.parents[value] = this.find(this.parents[value]);
61+
}
62+
63+
return this.parents[value];
64+
}
65+
66+
// O(alpha(n)), approximately O(1) time and space
67+
// where n is the total numbe of values
68+
union(valueOne, valueTwo) {
69+
if (!(valueOne in this.parents) || !(valueTwo in this.parents)) return;
70+
71+
const valueOneRoot = this.find(valueOne);
72+
const valueTwoRoot = this.find(valueTwo);
73+
if (this.ranks[valueOneRoot] < this.ranks[valueTwoRoot]) {
74+
this.parents[valueOneRoot] = valueTwoRoot;
75+
} else if (this.ranks[valueOneRoot] > this.ranks[valueTwoRoot]) {
76+
this.parents[valueTwoRoot] = valueOneRoot;
77+
} else {
78+
this.parents[valueTwoRoot] = valueOneRoot;
79+
this.ranks[valueOneRoot] += 1;
80+
}
81+
}
82+
}

0 commit comments

Comments
 (0)