mediumGraphsGoogleFacebook
Union-Find Tree Validator
An ops reviewer checks whether a hardware wiring diagram with n nodes and some bidirectional cables forms a single acyclic tree.
Given n nodes and an edge list of an undirected graph, determine if it is a valid tree (connected, no cycles).
Choose approach
0
1
2
3
4
1/5
Narrationstep 1 of 5
Union (0,1): components merged.
Variables
a=0
b=1
merged=0→1
How to think about it
- Edge count ≠ n-1 -> not a tree.
- Any edge joining two already-connected nodes -> cycle.
- Otherwise connected & acyclic.
Edge cases to catch in interview
- n = 1, no edges -> true.
- Multiple components with n-1 edges -> false.
Examples
Example 1
false{"n":4,"edges":[[0,1],[2,3]]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed