FastPrepNumber of Connected Components in an Undirected Graph

Number of Connected Components in an Undirected Graph

Google logoGoogle● MediumINTERNNEW GRADPHONE SCREEN
Learn

Problem statement

You are given an undirected graph with n vertices labeled from 0 to n - 1 and an edge list edges. Return the number of connected components in the graph.

Function

countComponents(n: int, edges: int[][]) → int

Examples

Example 1

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

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

Example 2

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

Every vertex is connected through one chain.

Example 3

n = 4edges = []return = 4

With no edges, each vertex forms its own component.

Constraints

  • 1 <= n <= 2000.
  • 0 <= edges.length <= 5000.
  • edges[i].length = 2.
  • 0 <= edges[i][0], edges[i][1] < n.
  • There are no self-loops or duplicate edges.

More Google problems

See Google hiring insights
public int countComponents(int n, int[][] edges) {
    // Write your code here.
}
n5
edges[[0,1],[1,2],[3,4]]
expected2
Checking account…