Use it when an undirected graph may contain multiple disconnected groups, including isolated vertices, and the task asks how many maximal reachable groups exist.
Keep true
After processing outer-loop starts below the current index, every vertex in their components is seen and components equals the number of DFS launches. A seen vertex can never launch another count.
Reuse it
A global visited set partitions a graph: every new search root contributes one component and consumes all vertices that must not contribute again. This transfers to islands, provinces, and cluster counting.
Build both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does visiting nodes 1 and 2 not add components, while visiting isolated node 5 does?
Sources and provenance
Full interview answer 24 min read
Count the separate connected groups in an undirected graph, including vertices that have no edges.
Problem
Input. A nonnegative node_count and undirected edge pairs with integer endpoints from 0 through node_count - 1.
Output. Return the number of connected components among all declared vertices.
Rules. Vertices belong together if an undirected path connects them, directly or through other vertices.
Every isolated vertex forms its own component. Repeated edges and self-loops do not merge additional components.
Preserve the inputs. Zero vertices returns zero.
Example. Five vertices and edges [[0, 1], [1, 2], [3, 4]] return 2.
The components are {0, 1, 2} and {3, 4}; six vertices without edges return 6.
Picture
With six nodes and edges 0-1, 0-2, 3-4, the groups are {0,1,2}, {3,4}, and {5}.
New start
After its flood
Later starts skipped
0
seen={0,1,2}, components=1
1 and 2
3
seen={0,1,2,3,4}, components=2
4
5
seen={0,1,2,3,4,5}, components=3
None
Node five still launches a flood. Its stack empties immediately because it has no neighbors.
This is permanent component coverage with explicit vertices instead of grid cells.
An unseen start cannot belong to a completed flood: that flood would have reached it.
Each launch therefore counts one new component, and its full coverage prevents double counting.
Mark a vertex before pushing it. seen means discovered, not fully expanded; a pending vertex must not be scheduled again.
The LIFO stack expands the first group in order 0,2,1.
Duplicate edges and self-loops do not change these groups, but they still require scans.
Do not use this undirected flood to count directed strongly connected components.
Problem trace
Separate union-find comparison: a duplicate union cannot remove a group
Read it this way:Four nodes begin as four components. Joining (0,1) and (2,3) leaves two; joining (1,0) again does not reduce that count. Which actual group would disappear if the duplicate union incorrectly decremented two to one?
Reference drawing
Problem trace
Count new traversals, not every node reached within them
Execution trace
Input and goalCount separate groups in an undirected graph.
Build the graph and initializeBuild both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0.
Use it when an undirected graph may contain multiple disconnected groups, including isolated vertices, and the task asks how many maximal reachable groups exist.
Keep true
After processing outer-loop starts below the current index, every vertex in their components is seen and components equals the number of DFS launches. A seen vertex can never launch another count.
Reuse it
A global visited set partitions a graph: every new search root contributes one component and consumes all vertices that must not contribute again. This transfers to islands, provinces, and cluster counting.
Build both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does visiting nodes 1 and 2 not add components, while visiting isolated node 5 does?
Read it this way:Four nodes begin as four components. Joining (0,1) and (2,3) leaves two; joining (1,0) again does not reduce that count. Which actual group would disappear if the duplicate union incorrectly decremented two to one?
Code
def count_components(node_count: int, edges: list[list[int]]) -> int: graph = [[] for _ in range(node_count)] for first, second in edges: graph[first].append(second) graph[second].append(first) seen: set[int] = set() components = 0 for start in range(node_count): if start in seen: continue components += 1 seen.add(start) stack = [start] while stack: for neighbor in graph[stack.pop()]: if neighbor not in seen: seen.add(neighbor) stack.append(neighbor) return components
Expected work is O(V+E). Total storage is O(V+E) for adjacency plus O(V) for seen and the stack.
Change the Component Summary
Start from count_components. Keep the same permanent marks and change what each completed flood contributes.
Return group sizes.
New task: Return the cardinality of each component.
Picture and change: Count one vertex per pop. Append the size only when that component’s stack empties.
Code: Complete replacement:
def component_sizes(node_count, edges): graph = [[] for _ in range(node_count)] for first, second in edges: graph[first].append(second) graph[second].append(first) seen, sizes = set(), [] for start in range(node_count): if start in seen: continue seen.add(start) stack, size = [start], 0 while stack: node = stack.pop() size += 1 for neighbor in graph[node]: if neighbor not in seen: seen.add(neighbor) stack.append(neighbor) sizes.append(size) return sorted(sizes)
Check: The example gives [1,2,3], whose sum is six. With four isolated vertices, return [1,1,1,1].
Use when: Group-size distribution matters. Sorting stabilizes output, not connectivity. For C components it adds O(Clog(C+1)) work to the flood.
Count unreachable unordered pairs.
New task: Count vertex pairs lying in different components, without listing every pair.
Picture and change: Remove a whole group’s size from remaining, then pair that group with every still-unprocessed vertex.
No vertex within the same component contributes. Every cross-component pair contributes when its earlier group is processed.