Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Count Connected Components

Graphsmedium

Given `n` nodes labeled `0..n-1` and an undirected `edges` list of `[a, b]` pairs, implement `countComponents(n, edges)` returning the number of connected components.

Sample tests

Input: countComponents(5, [[0,1],[1,2],[3,4]])
Output: 2
Input: countComponents(5, [[0,1],[1,2],[2,3],[3,4]])
Output: 1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Treating directed edges as one-way when the graph is undirected.

Learning resources

  • Wikipedia: Graph traversal
Approach & explanation (try first)

Counting DFS launches over unvisited nodes gives the component count in O(V + E).

Loading...
⌘/Ctrl + Enter

Run your code to see results.