Union Find Disjoint Set Data Structure in DSA C# - Time & Space Complexity
We want to understand how fast the Union Find data structure works when connecting groups and checking if elements belong to the same group.
How does the time needed change as we add more elements and connections?
Analyze the time complexity of the following code snippet.
public class UnionFind {
private int[] parent;
private int[] rank;
public UnionFind(int size) {
parent = new int[size];
rank = new int[size];
for (int i = 0; i < size; 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 a Union Find structure that groups elements and finds their group leaders efficiently using path compression and rank.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The Find method uses recursion with path compression to find the group leader.
- How many times: Each Union or Find call may trigger multiple Find calls, but path compression reduces repeated work over time.
As we add more elements, each Find or Union operation takes slightly more time at first, but path compression keeps it very fast.
| Input Size (n) | Approx. Operations per Find/Union |
|---|---|
| 10 | About 2-3 steps |
| 100 | About 4-5 steps |
| 1000 | About 6-7 steps |
Pattern observation: The number of steps grows very slowly, almost like a flat line, thanks to path compression.
Time Complexity: O(α(n)) per operation, where α(n) is the inverse Ackermann function.
This means each Union or Find runs almost in constant time, even for very large inputs.
[X] Wrong: "Each Find or Union takes linear time because it might traverse many elements."
[OK] Correct: Path compression and rank keep the trees very flat, so the actual steps per operation are extremely small, not linear.
Understanding this time complexity shows you know how efficient grouping works behind the scenes, a skill useful in many problems involving connected components or networks.
"What if we removed path compression from Find? How would the time complexity change?"
Practice
Union Find Disjoint Set data structure?Solution
Step 1: Understand the role of Union Find
The Union Find data structure is designed to keep track of which elements belong to which groups or sets, especially when these groups merge over time.Step 2: Compare with other data structures
Sorting elements or storing key-value pairs are not the main goals of Union Find. It focuses on connectivity and grouping.Final Answer:
To efficiently track and merge groups of connected elements -> Option CQuick Check:
Union Find = track and merge groups [OK]
- Confusing Union Find with sorting algorithms
- Thinking it stores key-value pairs like a dictionary
- Assuming it manages priority queues
Solution
Step 1: Recall C# object initialization syntax
In C#, to create a new object, we use thenewkeyword followed by the constructor call with parameters.Step 2: Check each option
var uf = new UnionFind(5); uses correct syntax:var uf = new UnionFind(5);. UnionFind uf = UnionFind(5); missesnew. var uf = UnionFind.New(5); uses a non-standard method. UnionFind uf = new UnionFind[] {5}; tries to create an array incorrectly.Final Answer:
var uf = new UnionFind(5); -> Option BQuick Check:
Use 'new' keyword for object creation [OK]
- Omitting the 'new' keyword
- Using array syntax instead of constructor
- Calling non-existent static methods
var uf = new UnionFind(5); uf.Union(0, 1); uf.Union(1, 2); bool connected = uf.Connected(0, 2); Console.WriteLine(connected);
What will be the output?
Solution
Step 1: Analyze the union operations
First, elements 0 and 1 are united, then 1 and 2 are united. This means 0, 1, and 2 are all connected.Step 2: Check the connectivity query
The calluf.Connected(0, 2)checks if 0 and 2 are in the same set, which they are after the unions.Final Answer:
True -> Option DQuick Check:
Union chains connect 0 and 2 = True [OK]
- Assuming only direct unions connect elements
- Confusing union with assignment
- Ignoring transitive connectivity
var uf = new UnionFind(3); uf.Union(0, 1); uf.Union(1, 3); Console.WriteLine(uf.Connected(0, 3));
What is the problem with this code?
Solution
Step 1: Check Union Find size and indices used
The Union Find is initialized with size 3, so valid indices are 0, 1, and 2.Step 2: Identify invalid index usage
The code callsuf.Union(1, 3)anduf.Connected(0, 3), but index 3 is invalid and out of range.Final Answer:
Index 3 is out of range for Union Find of size 3 -> Option AQuick Check:
Indices must be within 0 to size-1 [OK]
- Using indices equal to size or larger
- Assuming Union Find auto-expands
- Ignoring runtime exceptions from invalid indices
Solution
Step 1: Track unions step-by-step
Initially, sets are {0}, {1}, {2}, {3}, {4}, {5} (6 sets).
Union(0,1) merges {0} and {1} -> {0,1}, {2}, {3}, {4}, {5} (5 sets).
Union(2,3) merges {2} and {3} -> {0,1}, {2,3}, {4}, {5} (4 sets).
Union(4,5) merges {4} and {5} -> {0,1}, {2,3}, {4,5} (3 sets).
Union(1,2) merges sets containing 1 and 2 -> {0,1,2,3}, {4,5} (2 sets).Step 2: Count remaining distinct sets
After all unions, only two sets remain: {0,1,2,3} and {4,5}.Final Answer:
2 -> Option AQuick Check:
Count sets after unions = 2 [OK]
- Counting unions instead of sets
- Forgetting transitive merges
- Assuming each union reduces sets by one always
Ready to prove it?
Pass the test and this pattern moves unknown
