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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code