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-FindChecking 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
- Find the root of the first item.
- Find the root of the second item.
- If both roots are the same, the items are connected.
- 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}?
- Find root of 4 → say, root is 1
- Find root of 5 → root is 5 (its own root, separate group)
- Roots differ (1 vs 5)
Output: false (not connected)
Press ▶ Run to watch it step by step.
def connected(parent, a, b):
return find(parent, a) == find(parent, b)
# Same root => same component
# example: connectedBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.