2daysbeforeinterview
Home1Companies2Problems3Experiences4Compensation5Assistant

Spaces

Saved work

Your prep

Notes6Bookmarks7Submissions

Community

Leaderboard8Send feedback
Contribute9
2daysbeforeinterview
2daysbeforeinterview

Straight from the interview room.

Browse

  • Companies
  • Problems
  • Experiences
  • Compensation
  • Leaderboard
  • Pricing

Contribute

  • Add a question
  • Share an experience
  • Report compensation
  • Committed Contributor
  • Send feedback

About

  • About 2daysbeforeinterview
  • Contact
  • Privacy
  • Terms
  • Refunds
  • Delivery

© 2026 2daysbeforeinterview

  • Instagram(opens in a new tab)
  • YouTube(opens in a new tab)
  • X (Twitter)(opens in a new tab)
  • help@2daysbeforeinterview.com
HomeCompaniesProblems
Keep holding ⌥Alt and press a number · ? for every shortcut
Back
DSA
1 reportlast asked …
Arcana

Connected components in a graph

Given an undirected graph with n vertices labelled 0 to n - 1 and a list of undirected edges, return the number of connected components. A component is a maximal set of vertices mutually reachable from one another.

The graph may be disconnected, may contain isolated vertices, and edges may repeat an edge or contain a self-loop ([v, v]).

Example 1

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

There are 2 components: {0,1,2} and {3,4}.

Example 2

Input:  n = 4, edges = []
Output: 4

With no edges, every vertex is its own component.

Example 3

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

The repeated edge and the self-loop change nothing: the components are {0,1}, {2} and {3,4,5}.

Constraints

  • 1 <= n <= 10^5
  • 0 <= edges.length <= 2 * 10^5
  • edges[i].length == 2 and 0 <= edges[i][0], edges[i][1] < n

Hints

0/3

Domains

Backend
asked Jul 2025Report
Discussion
Related questions
Asked atArcana
My notes
Practice
EditorialLocked
Community solutions
Learning resources(3)
Arcana
Arcana