-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathUnionFind.java
More file actions
67 lines (58 loc) · 1.75 KB
/
UnionFind.java
File metadata and controls
67 lines (58 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Metadata Header (MANDATORY)
// -----------------------------
// Program Title: Union-Find (Disjoint Set Union)
// Author: [KotlinKing]
// Date: 2025-10-10
//
// Description: Implements the Disjoint Set Union data structure, or Union-Find.
// It includes the two essential optimizations: Path Compression and Union by Rank.
//
// Language: Java
//
// Time Complexity: O(α(n)) for find/union.
// Space Complexity: O(n).
// -----------------------------
public class UnionFind {
private int[] parent;
private int[] rank;
// Initialize n disjoint sets
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
// Find root of x with path compression
public int find(int x) {
if(parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// Union two sets by rank
public boolean union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if(rootX == rootY) return false; // already in same set
if(rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if(rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
return true;
}
// Example usage
public static void main(String[] args) {
UnionFind uf = new UnionFind(5);
uf.union(0, 1);
uf.union(1, 2);
uf.union(3, 4);
System.out.println("Are 0 and 2 connected? " + (uf.find(0) == uf.find(2))); // true
System.out.println("Are 0 and 3 connected? " + (uf.find(0) == uf.find(3))); // false
}
}