oneby7

Graphs Traversing a graph

450. Number of Connected Components in an Undirected Graph

Medium

You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges is an edge between vertices u and v, and it can be used in both directions.

A connected component is a group of vertices in which every vertex can reach every other one along edges, and that no edge joins to a vertex outside the group. A vertex with no edges is a component on its own.

Return the number of connected components in the graph.

Example 1

0123456

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

Output: 3

Explanation: Vertices 0, 2 and 4 form one component, joined in a cycle. Vertices 1 and 5 form the second, and 3 and 6 the third.

Example 2

01234

Input: n = 5, edges = [[3, 1]]

Output: 4

Explanation: Vertices 1 and 3 form one component. Vertices 0, 2 and 4 have no edges, so each is a component on its own.

Example 3

0

Input: n = 1, edges = []

Output: 1

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ vi
  • No edge appears twice: [u, v] and [v, u] are the same edge.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.