MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / DSU

Class DSU

CountTheNumberOfCompleteComponents.java:27–65  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

25 }
26
27 class DSU {
28
29 int[] parent;
30 int[] size;
31
32 DSU(int n) {
33 parent = new int[n];
34 size = new int[n];
35 for(int i=0;i<n;i++){
36 parent[i] = i;
37 }
38 Arrays.fill(size, 1);
39 }
40
41 // Find root of component with path compression
42 int find(int node) {
43 if (parent[node] == node) {
44 return node;
45 }
46 parent[node] = find(parent[node]);
47 return parent[node];
48 }
49
50 void union(int node1, int node2) {
51 int rootParent1 = find(node1);
52 int rootParent2 = find(node2);
53
54 if (rootParent1 == rootParent2) {
55 return;
56 }
57 if (size[rootParent1] > size[rootParent2]) {
58 parent[rootParent2] = rootParent1;
59 size[rootParent1] += size[rootParent2];
60 } else {
61 parent[rootParent1] = rootParent2;
62 size[rootParent2] += size[rootParent1];
63 }
64 }
65 }
66}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected