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-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). 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

  1. Start at the given item.
  2. While the item's parent is not itself, move to its parent.
  3. Once the root is reached, that is the group's representative.
  4. (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)

  1. 4's parent is 3, move to 3
  2. 3's parent is 2, move to 2
  3. 2's parent is 2 (itself) — root found
  4. Path compression: point both 4 and 3 directly to 2

Output: Root is 2; 4 and 3 now point directly to 2

Try your own input
Union-Find: Introduction
Also called Disjoint Set — tracks groups of connected items, where each group has one representative ("root") item that identifies it.
0
root
1
root
2
root
3
root
4
root
5
root
6
root
7
root
Active Root
Union-Find: Introduction
Press ▶ Run to watch it step by step.
Python · Union-Find in Code
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 4
Input: Find the root of item 4, where 4 -> 3 -> 2 -> 2 (root)

Behind 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

TimeNearly O(1) amortized with path compression, O(log n) without it
SpaceO(1) extra iterative

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.