Tarjan's Strongly Connected Components - Problem

Given a directed graph represented as an adjacency list, find all strongly connected components (SCCs) using Tarjan's algorithm.

A strongly connected component is a maximal set of vertices such that for every pair of vertices u and v, there is a directed path from u to v and a directed path from v to u.

Input: An adjacency list where graph[i] contains all vertices that vertex i points to.

Output: A list of strongly connected components, where each component is a list of vertices.

Input & Output

Example 1 — Cycle with Isolated Node
$ Input: graph = [[1], [2], [0], []]
Output: [[0,1,2], [3]]
💡 Note: Vertices 0→1→2→0 form a cycle (strongly connected). Vertex 3 has no edges, so it's isolated.
Example 2 — Two Separate Cycles
$ Input: graph = [[1], [0], [3], [2]]
Output: [[0,1], [2,3]]
💡 Note: Two separate cycles: 0↔1 and 2↔3. Each cycle forms its own strongly connected component.
Example 3 — Single Vertex
$ Input: graph = [[]]
Output: [[0]]
💡 Note: Single vertex with no edges forms one SCC containing just itself.

Constraints

  • 1 ≤ graph.length ≤ 1000
  • 0 ≤ graph[i][j] < graph.length
  • graph[i] contains all vertices that vertex i points to

Visualization

Tap to expand
INPUTALGORITHMRESULT0123Graph: [[1],[2],[0],[]]Cycle: 0→1→2→0Isolated: 31Step234Start DFS, assign discovery timesUpdate low-link valuesDetect SCC root vertexPop stack to get SCCStack State2 (top)10 (root)SCC 1[0, 1, 2]SCC 2[3]Final Output:[[0,1,2], [3]]Two stronglyconnected componentsKey Insight:Tarjan's algorithm uses discovery times and a stack during a single DFS traversal.When a vertex's low-link value equals its discovery time, it's an SCC root - pop the stack to collect the component!TutorialsPoint - Tarjan's Strongly Connected Components | Advanced Graph Algorithm
Asked in
Google 25 Facebook 18 Microsoft 15 Amazon 12
23.4K Views
Medium Frequency
~35 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