Merge Components with Disjoint Sets
Core idea
A disjoint-set structure partitions integer IDs 0..n-1 into nonoverlapping components. parent[x] points toward a root; a root is its own parent. find follows links and can compress the path; union links roots, preferably the smaller tree to the larger. With size weighting and path compression, operations have near-constant amortized cost (inverse Ackermann). The structure merges groups; it does not support splitting them.
parent = [0,0,1,2]def find(x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return xprint(find(3))print(parent)print(find(3), parent)Path halving moves each visited node toward its grandparent; repeated finds shorten the path.
Union by size
parent = list(range(5))size = [1]*5def find(x): while x != parent[x]: parent[x] = parent[parent[x]] x = parent[x] return xdef union(a,b): a,b = find(a),find(b) if a == b: return False if size[a] < size[b]: a,b = b,a parent[b] = a size[a] += size[b] return Trueunion(0,1); union(2,3); union(1,3)print(find(0)==find(2),find(0)==find(4))print(union(0,3))The first four IDs become connected; 4 stays separate. A redundant union leaves size unchanged.
Common mistake
Only root sizes are authoritative. Validate IDs before indexing in real code; a negative index can silently target a different node. Do not compare parent values directly to test connectivity: compare roots.
Practice
Trace parent and root size after each union. Test a repeated union, an isolated ID and an invalid ID; add explicit bounds checks.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Disjoint sets
Check your understanding of disjoint sets.
What is printed?
p=[0,0,1]x=2while p[x]!=x: x=p[x]print(x)What is printed?
p=list(range(3));p[1]=0print(p[1]==p[0],p[2]==p[0])What does path compression preserve?
Which roots should union by size attach?