Data Structures · Visualization
Disjoint Set: Introduction
Disjoint Set / Union-Find
A disjoint set (or Union-Find) keeps track of a collection of items split into non-overlapping groups, and efficiently answers two questions: 'are these two items in the same group?' and 'merge these two groups into one'. Time: Nearly O(1) per operation (technically O(α(n)), an extremely slow-growing function) with both optimizations. Space: O(n).
Big-O: Nearly O(1) with path compression and union by rank/size.
Disjoint Set: Introduction
Disjoint Set / Union-FindA disjoint set (or Union-Find) keeps track of a collection of items split into non-overlapping groups, and efficiently answers two questions: 'are these two items in the same group?' and 'merge these two groups into one'. Internally, each group is represented as a small tree, where every item points toward a 'parent', and the topmost item (the one pointing to itself) acts as the group's representative or 'root'.
How Disjoint Set: Introduction Works
- Start with every item in its own separate group (each item is its own parent).
- To merge two groups, find each item's root and link one root to the other.
- To check if two items are in the same group, find both items' roots and compare them.
- Use optimizations (path compression, union by rank/size) to keep these operations extremely fast.
Disjoint Set: Introduction Worked Example
Input: 5 items {1,2,3,4,5}, initially all separate
- Each item starts as its own group: {1}, {2}, {3}, {4}, {5}
- Union(1,2): merges into {1,2}
- Union(3,4): merges into {3,4}
- Union(2,3): merges {1,2} and {3,4} into {1,2,3,4}
Output: Groups: {1,2,3,4}, {5}
Press ▶ Run to watch it step by step.
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
# Each element points to a parent.
# The ROOT identifies its connected set.
# example: introDisjoint Set: Introduction Time & Space Complexity
When to Use Disjoint Set: Introduction
- Detecting cycles in an undirected graph
- Building a minimum spanning tree with Kruskal's algorithm
- Finding connected components in a network
- Image processing (grouping connected pixels/regions)
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.