Union-find
- Algorithms course
- Advanced
- Lesson 49/56
- 4 min
Union-find merges disjoint sets.
Union-find
Union-find tracks a graph's nodes in sets. find(x) locates x's root; union(x, y) merges two sets.
This structure is used in Kruskal's cycle check. Each node points to a parent; the root points to itself.
Parent array
Each node has a parent. Initially each node is its own parent: parent[i] = i. When merged, the parent is updated.
Finding the root follows the parent chain: while parent[x] != x: x = parent[x]. This loop continues until the root is found.
Practice init_parent function
Write init_parent(n). Return a parent array where each node is its own parent. Print it with print(init_parent(4)).
Starter code
def init_parent(n):
# Return parent arraySample solution
def init_parent(n):
# Return parent array
return list(range(n))
print(init_parent(4))Expected output
[0, 1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does find(x) return?
- x's root Correct answer
- Its own root
- Its neighbors
- Its weight
Explanation: find(x) returns x's root.
2 Initial parent
parent[i] = ____
parent[i] = i
Explanation: i is right.
3 Union-find: match the terms
| Term | Meaning |
|---|---|
find |
Find root |
union |
Merge sets |
parent |
Parent array |
root |
Self |