|
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 |
| - |
6 | 1 | class UnionFind {
|
7 | 2 | constructor() {
|
8 | 3 | this.parents = {};
|
@@ -38,3 +33,50 @@ class UnionFind {
|
38 | 33 | }
|
39 | 34 | }
|
40 | 35 | }
|
| 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