Skip to the solution
MediumDSA13 min read

How do you count connected components in an undirected graph?

717 views

The problem

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.

  • graphs
  • union-find
  • dfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonCount components three ways: DFS, BFS, Union-Find
PythonLabel the components, and a 100,000-vertex random graph

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 70 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is a heap / priority queue?

Continue