Question presented to candidate: "You are given n nodes labelled 0 to n โ 1 and a list of undirected edges. Write a Python function that returns the number of connected components."
What a strong answer should cover:
- Build an adjacency list sized by n (so isolated nodes are not lost), then start a DFS/BFS from every unvisited node; the number of starts is the answer.
- The Union-Find alternative: components = n โ successful unions; duplicates, self-loops and cycle edges are skipped automatically.
- O(V + E) time for traversal; O(E ยท ฮฑ(V)) for Union-Find, with O(V) space and no adjacency list.
- Edge cases: no edges, isolated nodes, duplicate edges, self-loops.
- Python details: iterative DFS with a list as the stack or BFS with
collections.deque(recursive DFS fails beyond about 1000 levels),[[] for _ in range(n)]for the adjacency list.
Clarifying questions expected:
- Is n given separately (can there be nodes with no edges)?
- Can edges repeat or be self-loops?
- Do you need the components themselves or just the count?
Code / implementation expected: Yes โ a traversal-based count and/or a Union-Find count, in Python.