Union Find Disjoint Set Data Structure in DSA Java - Time & Space Complexity
We want to understand how fast the Union Find data structure works when connecting or checking groups.
How does the time needed grow as we add more items?
Analyze the time complexity of the following code snippet.
public class UnionFind {
private int[] parent;
private int[] rank;
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
}
public int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) parent[rootX] = rootY;
else if (rank[rootX] > rank[rootY]) parent[rootY] = rootX;
else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
}
This code creates groups of connected items and quickly finds which group an item belongs to.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
findmethod uses recursion to find the group's root. - How many times: Each
findcall may recurse up the tree, but path compression makes this very fast over time. - Union calls: Use
findtwice and then connect groups if needed.
As we add more items, each find or union takes almost constant time thanks to path compression and rank balancing.
| Input Size (n) | Approx. Operations per find/union |
|---|---|
| 10 | About 2-3 steps |
| 100 | About 3-5 steps |
| 1000 | About 4-6 steps |
Pattern observation: The steps grow very slowly, almost flat, even as input grows large.
Time Complexity: O(α(n)) (Inverse Ackermann function)
This means each operation runs almost in constant time, even for very large inputs.
[X] Wrong: "Each find or union takes linear time because it may traverse many parents."
[OK] Correct: Path compression flattens the structure, so repeated operations become very fast, not linear.
Understanding this data structure's time complexity shows you can handle efficient grouping and connectivity problems, a common skill in coding challenges.
"What if we removed path compression from the find method? How would the time complexity change?"
Practice
Union Find Disjoint Set data structure?Solution
Step 1: Understand the purpose of Union Find
The Union Find data structure is designed to keep track of elements partitioned into disjoint sets and quickly find which set an element belongs to.Step 2: Compare with other options
Sorting, key-value storage, and queue operations are unrelated to Union Find's main goal.Final Answer:
To efficiently manage and query connected components in a set -> Option AQuick Check:
Union Find = Manage connected components [OK]
- Confusing Union Find with sorting algorithms
- Thinking it stores key-value pairs like a map
- Assuming it implements queue operations
Solution
Step 1: Recognize typical Union Find constructor
Usually, Union Find is initialized by passing the number of elements to its constructor, likenew UnionFind(5).Step 2: Check other options for syntax errors
UnionFind uf = new UnionFind(); uf.init(5); suggests a separate init method which is uncommon; UnionFind uf = new UnionFind[5]; tries to create an array of UnionFind objects, not a single instance; UnionFind uf = new UnionFind(0, 5); uses two parameters which is not standard.Final Answer:
UnionFind uf = new UnionFind(5); -> Option CQuick Check:
Constructor with size parameter = UnionFind uf = new UnionFind(5); [OK]
- Trying to create an array of UnionFind instead of one instance
- Using multiple parameters in constructor incorrectly
- Assuming an init method is required after construction
UnionFind uf = new UnionFind(5); uf.union(0, 1); uf.union(1, 2); boolean connected = uf.connected(0, 2); System.out.println(connected);What will be the output?
Solution
Step 1: Trace union operations
First, 0 and 1 are joined, then 1 and 2 are joined. This means 0, 1, and 2 belong to the same set.Step 2: Check connected query
Querying if 0 and 2 are connected returns true because they share the same root after unions.Final Answer:
true -> Option DQuick Check:
Union chains connect 0 and 2 = true [OK]
- Assuming union does not link transitive elements
- Confusing union with overwrite of sets
- Expecting false because 0 and 2 were not directly united
UnionFind uf = new UnionFind(3); uf.union(0, 1); uf.union(1, 2); System.out.println(uf.connected(0, 3));
Solution
Step 1: Check the size and indices used
The UnionFind is initialized with size 3, so valid indices are 0, 1, and 2. Index 3 is invalid.Step 2: Identify the error at connected call
Callingconnected(0, 3)accesses an invalid index, causing an index out of bounds error.Final Answer:
Index out of bounds error at connected(0, 3) -> Option AQuick Check:
Invalid index access = Index out of bounds error [OK]
- Assuming connected returns false for invalid index
- Ignoring array bounds in Union Find
- Thinking compilation error occurs instead of runtime error
union(0,1), union(2,3), union(4,5), union(1,2), how many distinct sets remain?Solution
Step 1: Analyze unions step-by-step
Initially, sets are {0}, {1}, {2}, {3}, {4}, {5}. - union(0,1) merges {0} and {1} -> {0,1} - union(2,3) merges {2} and {3} -> {2,3} - union(4,5) merges {4} and {5} -> {4,5} - union(1,2) merges sets containing 1 and 2 -> merges {0,1} and {2,3} -> {0,1,2,3}Step 2: Count remaining distinct sets
After all unions, sets are {0,1,2,3} and {4,5}, so total 2 sets remain.Step 3: Re-examine options
Options say 3, 2, 1, 4. The correct count is 2.Final Answer:
2 -> Option BQuick Check:
Union merges sets, final count = 2 [OK]
- Counting unions instead of distinct sets
- Forgetting transitive merges
- Assuming each union reduces sets by one without checking connections
Ready to prove it?
Pass the test and this pattern moves unknown
