Data Structures · Visualization

Disjoint Set: Connected?

Disjoint Set / Union-Find

Checking whether two items are connected (in the same group) is simply a matter of finding the root of each item and comparing them — if the roots match, the items are in the same group; if not, they belong to different groups. Time: Nearly O(1) amortized. Space: O(1) extra.

Big-O: Nearly O(1) with path compression and union by rank/size.

Disjoint Set: Connected?

Disjoint Set / Union-Find

Checking whether two items are connected (in the same group) is simply a matter of finding the root of each item and comparing them — if the roots match, the items are in the same group; if not, they belong to different groups.

How Connected? Works

  1. Find the root of the first item.
  2. Find the root of the second item.
  3. If both roots are the same, the items are connected.
  4. If the roots differ, the items are in separate groups.

Connected? Worked Example

Input: Are items 4 and 5 connected, given groups {1,2,3,4} and {5}?

  1. Find root of 4 → say, root is 1
  2. Find root of 5 → root is 5 (its own root, separate group)
  3. Roots differ (1 vs 5)

Output: false (not connected)

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 connected(parent, a, b):
    return find(parent, a) == find(parent, b)

# Same root => same component
# example: connected
Input: Are items 4 and 5 connected, given groups {1,2,3,4} and {5}?

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.

Connected? Time & Space Complexity

TimeNearly O(1) amortized
SpaceO(1) extra

When to Use Connected?

  • Checking if adding an edge would create a cycle in a graph
  • Verifying whether two accounts/entities are linked in a network
  • Answering 'same component?' queries in dynamic connectivity problems

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.