Summary - Advanced structures
- Algorithms course
- Advanced
- Lesson 52/56
- 4 min
Print union-find set merges in a mini task.
Summary - Advanced structures
In this group you learned three advanced structures: union-find, trie and segment tree. Each serves a different purpose: sets, prefixes, ranges.
Now you will write a function that deepens union-find. This summary unites the group's first concept in a single piece of code.
Practice count_sets function
Write count_sets(n). init_parent is given; do union(0,1) and union(2,3), return the number of distinct roots. Print 2 with print(count_sets(4)).
Starter code
def init_parent(n):
# Return parent array
return list(range(n))
def count_sets(n):
# Count distinct sets after unionsSample solution
def init_parent(n):
# Return parent array
return list(range(n))
def count_sets(n):
# Count distinct sets after unions
parent = init_parent(n)
def find(x):
while parent[x] != x:
x = parent[x]
return x
def union(x, y):
parent[find(x)] = find(y)
union(0, 1)
union(2, 3)
roots = set(find(i) for i in range(n))
return len(roots)
print(count_sets(4))Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does union-find track?
- A single node
- Edge weights
- Ranges
- Sets Correct answer
Explanation: Union-find tracks sets.
2 find loop
while parent[x] ____ x:
while parent[x] != x:
Explanation: != is right.
3 Summary - Advanced structures: match the terms
| Term | Meaning |
|---|---|
union-find |
Sets |
trie |
Prefixes |
segment tree |
Ranges |
parent |
Parent |