Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Number of Connected Components in an Undirected Graph

Medium
graphunion-findbfsdfs

Given n nodes and a list of undirected edges, return the number of connected components.

Input

  • Line 1: n m
  • Next m lines: u v

Output: the component count.

Example 1
Input:
5 3
0 1
1 2
3 4
Output:
2
Example 2
Input:
5 4
0 1
1 2
2 3
3 4
Output:
1

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ m ≤ 5000
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.