Number of Connected Components in an Undirected Graph

MediumGraphs

You get n nodes, numbered 0 to n - 1, and a list of undirected edges, where [a, b] joins node a and node b.

Return how many connected components the graph has: groups of nodes that can reach each other along the edges. A node with no edges is a component of its own.

Examples

Example 1
Input:  n = 6, edges = [[0, 1], [1, 2], [3, 4]]
Output: 3

The groups are {0, 1, 2}, {3, 4} and {5} on its own.

Example 2
Input:  n = 4, edges = [[0, 1], [1, 2], [2, 3], [3, 0]]
Output: 1

The four edges make one ring through every node.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • 0 ≤ a, b < n and a ≠ b
  • No edge appears twice.

Stuck?

Hint 1

Start with n separate groups. Every edge that joins two different groups merges them into one.

Hint 2

Use union-find: find the root of each end, and when the roots differ, link one root to the other and subtract one from the count. Linking the nodes themselves instead of their roots loses groups.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur