Number of Connected Components in an Undirected Graph
Beginner Mode

Problem Statement

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.

Return the number of connected components in the graph.

A connected component is a maximal set of nodes such that each pair of nodes is connected by a path, and no node outside the set is connected to any node in the set.

Additional information

  • 1 <= n <= 2000
  • 1 <= edges.length <= 5000
  • edges[i].length == 2
  • 0 <= ai <= bi < n
  • ai != bi
  • There are no repeated edges.

Example 1:

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

Output: 2

Explanation: Nodes 0, 1, and 2 form one connected component. Nodes 3 and 4 form a second connected component.

Example 2:

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

Output: 1

Explanation: All nodes are connected in a single path, forming exactly 1 component.

Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →