Skip to content

Commit e437f7b

Browse files
committed
using union fjnd to identify the edge that can bring cycle in graph
1 parent bf4b49e commit e437f7b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

UnionFind/redundantConnection.java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
/*
3+
Union Find will ensure that when 2 points in the edge have same parent, we won't be able
4+
to union them as they will create a cycle in graph.
5+
Using union by rank and path compression O(N) can be reduced to O(logN).
6+
*/
7+
public int[] findRedundantConnection(int[][] edges) {
8+
int n = edges.length;
9+
UnionFind uf = new UnionFind(n+1); // since edges start from 1, hence we use n+1.
10+
for (int[] e: edges) {
11+
if (!uf.union(e[0], e[1])) { // if we can't union, means they have same parent and we can't union because it will create a loop, hence this is redundant connection
12+
return e;
13+
}
14+
}
15+
return new int[0];
16+
}
17+
}
18+
19+
class UnionFind {
20+
int parent[];
21+
int size[];
22+
23+
24+
public UnionFind(int n) {
25+
parent = new int[n];
26+
size = new int[n];
27+
for (int i=0; i<n; i++) {
28+
parent[i] = i;
29+
}
30+
}
31+
32+
public int find(int p) {
33+
while(p != parent[p]) {
34+
p = parent[p];
35+
}
36+
return p;
37+
}
38+
39+
public boolean union(int p, int q) {
40+
int pParent = find(p);
41+
int qParent = find(q);
42+
43+
if (pParent == qParent) { // means they are already in same set and cannot be unioned
44+
return false; //hence we return false, it means they have a circle
45+
}
46+
if (size[pParent] < size[qParent]) { // attaching smaller set to larger set
47+
parent[pParent] = qParent;
48+
size[qParent]++;
49+
} else {
50+
parent[qParent] = pParent;
51+
size[pParent]++;
52+
}
53+
return true; //if we can union them, we return true
54+
}
55+
}

0 commit comments

Comments
 (0)