Count connected groups
Nodes are connected by undirected edges. Count the separate groups, where two nodes are in the same group if a path joins them.
count_components(
[1, 2, 3, 4], [(1, 2), (2, 3)])
# 2: {1, 2, 3} and {4}Depth-first search
Build an adjacency dict that lists each edge in both directions. Then, for every node not yet visited, count one group and visit everything reachable from it.
Recursion looks natural here, but Python raises RecursionError at a depth of about 1000 frames by default. A chain of 5000 nodes would crash it. An explicit stack has no such limit:
stack = [start]
while stack:
node = stack.pop()
# visit, then push neighboursNodes with no edges still count as groups of one, so loop over nodes rather than over the edges.
Your task
Write count_components(nodes, edges) returning the number of connected groups, using an explicit stack. It must handle a chain of thousands of nodes.
The explanation opens here once every check passes.