CodeArchon

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.

1def validTree(n, edges):
2 if len(edges) != n - 1: return False
3 parent = list(range(n))
4 def find(x):
5 while parent[x] != x:
6 parent[x] = parent[parent[x]]
7 x = parent[x]
8 return x
9 for a, b in edges:
10 ra, rb = find(a), find(b)
11 if ra == rb: return False
12 parent[ra] = rb
13 return True
Variables
a=0
b=1
merged=0→1

How to think about it

  1. Edge count ≠ n-1 -> not a tree.
  2. Any edge joining two already-connected nodes -> cycle.
  3. Otherwise connected & acyclic.

Edge cases to catch in interview

  • n = 1, no edges -> true.
  • Multiple components with n-1 edges -> false.

Examples

Example 1false
{"n":4,"edges":[[0,1],[2,3]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed