Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Number of Connected Components in an Undirected Graph
Problem
You have n nodes labelled 0 through n - 1 and a list of undirected edges. Return how many connected components the graph has, counting isolated nodes as components of size one.
- There are at most 3,000 nodes and at most 8,000 edges.
- Edges are unordered pairs of distinct nodes; no duplicates.
Examples
n = 6, edges = [[0,1],[1,2],[3,4]]→3.{0,1,2},{3,4}, and the isolated node 5.n = 6, edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]→1. A single path through all six nodes.n = 4, edges = []→4. Every node is its own component.
Hints
- Start with every node in its own group. What happens to the number of groups when you process an edge between two nodes that are already in the same group?
- You need "which group is this node in" and "merge two groups" to be fast.
- Union-find: begin with
ncomponents, and decrement the count each time a union actually merges two different sets. Alternatively, DFS/BFS from each unvisited node and count the starts.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.