DIY: Number of Connected Components in an Undirected Graph

Solve the interview question "Number of Connected Components in an Undirected Graph" in this lesson.

Problem statement

Suppose you are given an undirected graph with n nodes. You are also given an integer n and an array edges where edges[i] = [xi, yi] indicates that there is an edge between xi and yi in the graph. Your task is to return the number of connected components in the graph.

A connected component is a maximal set of vertices of a graph such that for any pair of vertices u, v in that set, there is a path from u to v. The following illustration shows this behavior.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.