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.
Variables
a=0
b=1
count=4
How to think about it
- Component count = n − (successful unions).
- Union-by-path-compression keeps near-linear amortized cost.
- DFS/BFS variant is equivalent.
Edge cases to catch in interview
- No edges -> n.
- All connected -> 1.
Examples
Example 1
1{"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