Connected Components - Problem

Given an undirected graph represented as an adjacency list, find all connected components. A connected component is a maximal set of vertices where every vertex is reachable from every other vertex in the set through some path.

Return a 2D array where each inner array contains all the vertices that belong to the same connected component. The components can be returned in any order, and vertices within each component can also be in any order.

Input: graph - adjacency list representation where graph[i] is a list of all vertices connected to vertex i

Output: 2D array of connected components

Input & Output

Example 1 — Basic Connected Components
$ Input: graph = [[1,3],[0,3],[],[0,1]]
Output: [[0,1,3],[2]]
💡 Note: Vertices 0, 1, and 3 are connected (0↔1, 0↔3, 1↔3), forming one component. Vertex 2 has no connections, forming a separate component.
Example 2 — Single Component
$ Input: graph = [[1],[0,2],[1]]
Output: [[0,1,2]]
💡 Note: All vertices are connected in a line: 0↔1↔2, so there's only one connected component.
Example 3 — All Isolated
$ Input: graph = [[],[],[]]
Output: [[0],[1],[2]]
💡 Note: No edges exist, so each vertex forms its own connected component.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ graph[i].length ≤ n
  • 0 ≤ graph[i][j] ≤ n - 1
  • graph[i][j] ≠ i
  • All values in graph[i] are unique

Visualization

Tap to expand
INPUTGraph Adjacency List0132[[1,3],[0,3],[],[0,1]]ALGORITHMDFS Traversal Steps1Start DFS from vertex 02Visit neighbors 1 and 33Component [0,1,3] found4Start DFS from vertex 25Component [2] foundRESULTConnected ComponentsComponent 1Vertices: 0, 1, 3All connected via edgesComponent 2Vertex: 2 (isolated)Output: [[0,1,3],[2]]Key Insight:Use DFS/BFS with visited tracking to systematically explore each connected component exactly onceTutorialsPoint - Connected Components | DFS Approach
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
34.5K Views
High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen