VOOZH about

URL: https://www.geeksforgeeks.org/dsa/connected-components-in-an-undirected-graph/

⇱ Connected Components in an Undirected Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Connected Components in an Undirected Graph

Last Updated : 29 Oct, 2025

Given an undirected graph(the graph may contain one or more components) represented by an adjacency list adj[][], return all the connected components in any order.

Examples:

Input: adj[][] = [[2, 3], [2], [0, 1], [0], [5], [4]]

👁 420046859

Output: [[0, 1, 2, 3], [4, 5]]
Explanation: There are 2 different connected components. They are {0, 1, 2, 3} and {4, 5}.

Input: adj[][] = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]

👁 frame_3148

Output: [0, 1, 2, 3, 4]
Explanation: There is a single component, i.e., {0, 1, 2, 3, 4}.

[Approach 1]: Using Depth first search (DFS)

In this approach, we perform a DFS once for every connected component in the graph. Each DFS call starting from an unvisited node explores and marks all nodes belonging to that component. Hence, for each DFS call, we can store the nodes of that component.


Output
0 3 2 1 
4 5 

Time complexity: O(V + E). We visit every vertex at most once and every edge is traversed at most once.
Auxiliary Space: O(V + E), since an extra visited array of size V is required, and recursive stack size.

[Approach 2]: Using Breadth first search (BFS) - O(V+E) Time and O(V) Space

The main idea is to perform a BFS once for every connected component in the graph. Each BFS call starting from an unvisited node explores and marks all nodes belonging to that component. Hence, for each BFS call, we can store the nodes of that component.


Output
0 3 2 1 
4 5 

[Approach 3]: Using Disjoint Set Union (DSU) - O(V+E) Time and O(V) Space

The idea is to use Disjoint Set Union (DSU)to find all connected components in the graph. We unite the vertices connected by edges using union function and finally we get different vertices belonging to different components.


Output
4 5 
0 1 2 3 
Comment
Article Tags: