CodeArchon

mediumGraphsGoogle

Component Counter

A network analyst counts how many isolated subnets emerge from a list of peer-to-peer links across n machines.

Given n nodes and an edge list, return the number of connected components in the undirected graph.

Choose approach

0
1
2
3
4
1/4
Narrationstep 1 of 4

Merge components containing 0 and 1. count=4.

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

How to think about it

  1. Component count = n − (successful unions).
  2. Union-by-path-compression keeps near-linear amortized cost.
  3. DFS/BFS variant is equivalent.

Edge cases to catch in interview

  • No edges -> n.
  • All connected -> 1.

Examples

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

Try your own input

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