MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / UnionFind

Class UnionFind

famous-algorithms/union-find.js:1–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class UnionFind {
2 constructor() {
3 this.parents = {};
4 }
5
6 createSet(value) {
7 this.parents[value] = value;
8 }
9
10 //Time O(n) - space O(1)
11 find(value) {
12 if (this.parents.hasOwnProperty(value)) {
13 let currentParent = value;
14 while (currentParent !== this.parents[currentParent]) {
15 currentParent = this.parents[currentParent];
16 }
17 return currentParent;
18 } else {
19 return null;
20 }
21 }
22
23 //Time O(n) - space O(1)
24 union(valueOne, valueTwo) {
25 if (
26 this.parents.hasOwnProperty(valueOne) &&
27 this.parents.hasOwnProperty(valueTwo)
28 ) {
29 const valueOneRoot = this.find(valueOne);
30 const valueTwoRoot = this.find(valueTwo);
31
32 this.parents[valueTwoRoot] = valueOneRoot;
33 }
34 }
35}
36
37//
38// SOLUTION 2

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected