Skip to content
CodeShare
All problems

Connected Components

Count the separate groups in an undirected graph.

MediumGraphsUnion find

There are n nodes labeled 0 to n - 1, and an array edges where edges[i] = [a, b] is an undirected edge between nodes a and b.

Return the number of connected components in the graph.

Examples

Example 1
Input
n = 5, edges = [[0, 1], [1, 2], [3, 4]]
Output
2
Example 2
Input
n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
Output
1
Example 3
Input
n = 3, edges = []
Output
3
Why
With no edges, every node is its own component.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • No edge is repeated, and there are no self-loops.