Number of Connected Components solution explained
To count connected components in an undirected graph, start with every node as its own group and merge the two groups at the ends of each edge; the number of groups left is the answer. Union-find does this in nearly linear time, and a search that starts once from every unvisited node gives the same count in O(V + E). Nodes with no edges count as components of their own.
By Evin JohnPublished 8 min read
The problem, in plain terms
There are n devices on a floor, labeled 0 to n - 1, and a list of cables. Each cable connects two devices and works in both directions. Two devices are in the same network if a chain of cables links them. How many separate networks are there? A device with no cables at all is a network by itself.
Floor A: n = 7, cables = [0-4, 4-2, 1-5]
{0, 2, 4} {1, 5} {3} {6} answer: 4
Floor B: n = 5, cables = [0-1, 2-3, 3-4, 4-2, 1-0]
{0, 1} {2, 3, 4} answer: 2Floor A shows why n is part of the input: devices 3 and 6 appear in no cable, yet each is one of the four networks. Floor B shows two things that must not confuse the count. Devices 2, 3 and 4 form a loop, and the cable between 0 and 1 is listed twice. Neither changes the number of pieces.
Clarify the input size, whether cables can repeat or connect a device to itself, and whether you will be asked to report the count again as cables are added. That last question decides whether a one-shot search or union-find is the better starting point.
How it differs from Number of Islands
Both problems count connected components, but the graph arrives in different forms. In Number of Islands the graph is implicit: cells are nodes and you compute neighbors with arithmetic, and water cells are not nodes at all. Here the edges are given explicitly as a list, so you must build adjacency lists yourself or use union-find directly on the pairs, and every label from 0 to n - 1 is a node whether or not it has edges. Interviewers often ask this version to see whether you can build the graph, not just walk it.
A slow first approach: spread the smallest label
Give each node a label equal to its own number. Then sweep over all edges, and for each edge set both endpoints to the smaller of their two labels. Repeat full sweeps until one changes nothing. At that point every node in a piece carries that piece's smallest label, so the number of distinct labels is the answer. A long path can need about one sweep per node, so the worst case is O(V × E). It is simple and correct, and it makes a decent test oracle.
Optimal approach 1: union-find with union by size
Keep, for each node, a pointer toward a representative of its group. To find a node's group, follow pointers to the top. To merge two groups, point the smaller group's top at the larger one's. Start a counter at n and subtract one each time a merge actually joins two different groups. When all edges are processed, the counter is the number of components.
class Groups:
def __init__(self, n):
self.boss = list(range(n))
self.size = [1] * n
self.count = n
def find(self, x):
root = x
while self.boss[root] != root:
root = self.boss[root]
while self.boss[x] != root: # point the whole path at the root
self.boss[x], x = root, self.boss[x]
return root
def join(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.boss[rb] = ra
self.size[ra] += self.size[rb]
self.count -= 1
return True
def count_components(n, edges):
groups = Groups(n)
for a, b in edges:
groups.join(a, b)
return groups.countBecause this version uses both union by size and full path compression, each operation costs amortized O(α(n)), where α is the inverse Ackermann function and is at most four or so for any input you could store. A repeated cable or a self-loop finds the same root on both ends and simply returns without changing the count. The find loop is iterative, so long chains are safe.
Optimal approach 2: one search per new piece
Build adjacency lists, adding each cable in both directions. Then walk the nodes from 0 to n - 1. Whenever you reach a node that no earlier search has visited, it belongs to a new piece: add one to the count and run a search from it that marks everything reachable. Nodes with no cables still get their turn in the outer loop and are each counted once.
function countComponents(n, edges) {
const links = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
links[a].push(b);
links[b].push(a);
}
const seen = new Uint8Array(n);
let pieces = 0;
for (let start = 0; start < n; start++) {
if (seen[start]) continue;
pieces++;
seen[start] = 1;
const todo = [start];
while (todo.length > 0) {
const node = todo.pop();
for (const next of links[node]) {
if (!seen[next]) {
seen[next] = 1;
todo.push(next);
}
}
}
}
return pieces;
}Which should you pick? For a single question on a fixed edge list, both are linear and both are fine. Union-find wins when the edges arrive over time, when you never want to store adjacency lists, or when the follow-up asks for the count after every new edge. The search wins when you also need to list the members of each piece, since a search naturally visits them together.
The streaming follow-up
A common extension: cables are installed one at a time, and after each installation you must report the current number of networks. Rerunning a search after each cable costs O(V + E) per step. Union-find answers each step in near-constant time, because the counter is already maintained.
def counts_after_each(n, edges):
groups = Groups(n)
history = []
for a, b in edges:
groups.join(a, b)
history.append(groups.count)
return historyIf cables are removed instead of added, union-find cannot split groups. When all removals are known in advance, process them backward as additions. When they are not, the problem needs a dynamic connectivity structure, which is well beyond a standard interview; saying so is a good answer.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Smallest-label sweeps | O(V × E) worst case | O(V) |
| DFS or BFS from each unvisited node | O(V + E) | O(V + E) for adjacency lists and the stack |
| Union-find, size plus compression | O(V + E × α(V)), effectively linear | O(V) |
| Count after each of E additions | O(E × α(V)) total with union-find | O(V) |
Edge cases to try
- No edges at all: the answer is n.
- Every node joined into one piece: the answer is 1.
- A cable listed twice, or a cable from a node to itself: no effect.
- A piece that contains a loop: still one piece.
- A single long path: a check that the search or find loop does not recurse once per node.
- n = 0: the answer is 0.
Common mistakes
- Counting only nodes that appear in the edge list, which drops isolated nodes.
- Decrementing the counter for every edge, including edges inside a group that is already joined.
- Merging the two nodes instead of their roots, so groups never actually combine.
- Adding each undirected edge in one direction only, so a search from the wrong end misses part of a piece.
- Claiming the inverse Ackermann bound while using neither union by size nor rank.
How to explain it out loud
Fictional example
- Candidate
- Every node starts as its own component, so I begin the count at n. Each edge either joins two different components, which drops the count by one, or sits inside one, which changes nothing.
- Candidate
- Union-find tracks exactly that. I will merge by size and compress paths so every operation is close to constant time.
- Interviewer
- What if I also want the members of each network?
- Candidate
- Then I would rather run a search from each unvisited node, because it visits a whole piece at once and I can collect the nodes as I go. It is still linear.
Related problems
Redundant Connection uses the same merge step to find the one edge that closes a loop. Word Ladder builds a graph from strings and searches it by distance. Graph Valid Tree is this problem with a stricter goal: exactly one piece and no loops. All walkthroughs are on the coding problems hub.
Practicing with Natively
When you rehearse graph problems, it helps to compare your plan with a second opinion. Natively, a desktop app for Mac and Windows, can read the problem from a screenshot during practice and suggest union-find or a search, along with the isolated-node edge case. Its transcript of the mock session lets you check later whether you explained why the counter starts at n. The AI interview assistant page describes how it fits into practice.
Questions people ask
How do you count connected components in an undirected graph?
Start a counter at n and use union-find: for each edge, if its two endpoints have different roots, merge them and subtract one. Alternatively, run a DFS or BFS from every unvisited node and count how many searches you start.
What is the time complexity?
DFS or BFS is O(V + E). Union-find with union by size and path compression is O(V + E × α(V)), where α is the inverse Ackermann function, so it is effectively linear.
Do isolated nodes count as components?
Yes. A node with no edges is a component of its own. This is why n is part of the input and why you loop over every label from 0 to n - 1 rather than only nodes in the edge list.
When is union-find better than DFS for this problem?
When edges arrive one at a time and you need the count after each, or when you do not want to build adjacency lists. DFS is handier when you also need the members of each component.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
