Skip to problem
←

Strongly Connected Components

Medium 0 attempts

Given a directed graph with V vertices labeled 0 through V - 1, return all its strongly connected components.

A component is a maximal group in which every vertex can reach every other vertex by following directed edges. Maximal means you cannot add another vertex while retaining that property.

The adjacency list adj[u] contains the destinations of edges leaving vertex u. Edges are directed; an edge from u to v does not imply an edge back.

Return a partition of all vertices: include each vertex exactly once, including isolated vertices as singleton components. The order of components and the order of vertices within them do not matter.

Function contract

Implement findSCCs(V, adj).

Output: Return the maximal strongly connected components as arrays of vertex labels. Include each vertex exactly once. Component order and vertex order within each component do not matter.

Example 1

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

Explanation: Vertices 0, 1, and 2 form a directed cycle. The one-way edges from 2 to 3 and from 3 to 4 provide no return paths, so 3 and 4 are separate components.

Example 2

Input
V = 1
adj = [[]]
Output
[[0]]
Constraints
  • 1 <= V <= 5000
  • 0 <= E <= V*(V-1)
  • adj.length == V; adj[u] lists the destinations of directed edges from u
  • Vertices are labeled 0 through V - 1; no duplicate edges or self-loops

Iterative Kosaraju

Use explicit DFS frames to record vertices in finishing order. Traverse the reversed graph in reverse finishing order; each traversal yields one strongly connected component.

javascript
function findSCCs(V, adj) {
  const visited = Array(V).fill(false),
    order = [],
    reverse = Array.from({ length: V }, () => []);
  for (let u = 0; u < V; u++) for (const v of adj[u]) reverse[v].push(u);
  for (let start = 0; start < V; start++)
    if (!visited[start]) {
      const stack = [[start, 0]];
      visited[start] = true;
      while (stack.length) {
        const frame = stack[stack.length - 1],
          u = frame[0];
        if (frame[1] === adj[u].length) {
          order.push(u);
          stack.pop();
          continue;
        }
        const v = adj[u][frame[1]++];
        if (!visited[v]) {
          visited[v] = true;
          stack.push([v, 0]);
        }
      }
    }
  visited.fill(false);
  const result = [];
  while (order.length) {
    const start = order.pop();
    if (visited[start]) continue;
    const stack = [start],
      component = [];
    visited[start] = true;
    while (stack.length) {
      const u = stack.pop();
      component.push(u);
      for (const v of reverse[u])
        if (!visited[v]) {
          visited[v] = true;
          stack.push(v);
        }
    }
    result.push(component);
  }
  return result;
}

Time: O(V + E) | Space: O(V + E)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript