Data Structures · Visualization
Disjoint Set: Find
Disjoint Set / Union-Find
Find determines which group an item belongs to by following its chain of parent pointers upward until reaching the root (an item that is its own parent). Time: Nearly O(1) amortized with path compression, O(log n) without it. Space: O(1) extra iterative.
Big-O: Nearly O(1) with path compression and union by rank/size.
Disjoint Set: Find
Disjoint Set / Union-FindFind determines which group an item belongs to by following its chain of parent pointers upward until reaching the root (an item that is its own parent). To keep future finds fast, a technique called 'path compression' re-points every item visited along the way directly to the root, flattening the tree.
How Find Works
- Start at the given item.
- While the item's parent is not itself, move to its parent.
- Once the root is reached, that is the group's representative.
- (Path compression) Go back through the visited items and point them all directly to the root.
Find Worked Example
Input: Find the root of item 4, where 4 -> 3 -> 2 -> 2 (root)
- 4's parent is 3, move to 3
- 3's parent is 2, move to 2
- 2's parent is 2 (itself) — root found
- Path compression: point both 4 and 3 directly to 2
Output: Root is 2; 4 and 3 now point directly to 2
Press ▶ Run to watch it step by step.
def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x]) # compression
return parent[x]
# Nearly O(1) with path compression
# example: find 4Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Find Time & Space Complexity
When to Use Find
- Checking which network/cluster a node currently belongs to
- The core lookup used inside cycle detection and Kruskal's algorithm
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.