Blind 75
47 / 75Free practice

Number of Connected Components in an Undirected Graph

Medium · Graphs

On LeetCode, Number of Connected Components in an Undirected Graph needs LeetCode Premium (checked October 2026). Here it is free: run and submit in Python, JavaScript, Java or C++ with a free account.

Jump to code

Count connected components among n vertices labeled 0 through n−1, including isolated vertices, given a list of undirected edges.

Examples

Example 1

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

Output: 2

Example 2

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

Output: 1

Constraints

  • 1 <= n <= 100
  • 0 <= edges.length <= n * (n - 1) / 2
Need a hint?

A traversal from an unseen vertex visits exactly one component.

Asked in real interviews

Candidates reported versions of Number of Connected Components in an Undirected Graph from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  5,
  [
    [
      0,
      1
    ],
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ]
]
Expected
2
Case 2
Input
[
  5,
  [
    [
      0,
      1
    ],
    [
      1,
      2
    ],
    [
      2,
      3
    ],
    [
      3,
      4
    ]
  ]
]
Expected
1
Case 3
Input
[
  1,
  []
]
Expected
1
Case 4
Input
[
  4,
  [
    [
      0,
      1
    ],
    [
      2,
      3
    ]
  ]
]
Expected
2
Case 5
Input
[
  4,
  [
    [
      0,
      1
    ],
    [
      1,
      2
    ],
    [
      2,
      3
    ],
    [
      3,
      0
    ]
  ]
]
Expected
1

Drafts are saved per language in this browser when storage is available.