Kosaraju's algorithm

Pattern: Strongly connected components

medium

Count strongly connected components in two DFS passes. First, record vertices in the order they finish. Then, on the graph with every edge reversed, start a search from each unvisited vertex in reverse finishing order; each search collects exactly one component.

The problem

Return the number of strongly connected components of a directed graph: largest groups where every vertex can reach every other. Vertices are numbered from 0 and each edge is given as [u, v]. (from u to v).

Think first

  • What does finishing order give you?
  • Why reverse the graph?
  • What does one search in the second pass collect?

Hints

    Brute force, and why it fails

    For every pair of vertices, test reachability both ways: O(V × (V + E)).

    The key insight

    Finishing order plus the reversed graph peel off one component per search, in linear time.

    Dry run

    Edges 1 → 0, 0 → 2, 2 → 1, 0 → 3, 3 → 4. First pass finishes 4, 3, then 1, 2, 0.

    Step 1 of 3

    The plan

    pass 1: DFS, push on finish
    pass 2: on the reversed graph, pop vertices; each unvisited one starts a search = one SCC
    

    Complexity

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

    Two DFS passes.

    Edge cases

    • No edges: n components.
    • One big cycle: 1.
    • A DAG: n components.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int kosaraju(int n, int[][] edges) {
            List<List<Integer>> adj = new ArrayList<>(), rev = new ArrayList<>();
            for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); rev.add(new ArrayList<>()); }
            for (int[] e : edges) { adj.get(e[0]).add(e[1]); rev.get(e[1]).add(e[0]); }
            Deque<Integer> order = new ArrayDeque<>();   // vertices by finishing time, latest on top
            boolean[] seen = new boolean[n];
            for (int i = 0; i < n; i++) if (!seen[i]) finish(i, adj, seen, order);
            Arrays.fill(seen, false);
            int count = 0;
            while (!order.isEmpty()) {              // on the reversed graph, each search from the latest finisher is one SCC
                int u = order.pop();
                if (seen[u]) continue;
                count++;
                collect(u, rev, seen);
            }
            return count;
        }
    
        private void finish(int u, List<List<Integer>> adj, boolean[] seen, Deque<Integer> order) {
            seen[u] = true;
            for (int v : adj.get(u)) if (!seen[v]) finish(v, adj, seen, order);
            order.push(u);
        }
    
        private void collect(int u, List<List<Integer>> rev, boolean[] seen) {
            seen[u] = true;
            for (int v : rev.get(u)) if (!seen[v]) collect(v, rev, seen);
        }
    }

    C++

    class Solution {
    public:
        int kosaraju(int n, vector<vector<int>>& edges) {
            vector<vector<int>> adj(n), rev(n);
            for (const vector<int>& e : edges) { adj[e[0]].push_back(e[1]); rev[e[1]].push_back(e[0]); }
            vector<int> order;                      // vertices by finishing time
            vector<bool> seen(n, false);
            for (int i = 0; i < n; i++) if (!seen[i]) finish(i, adj, seen, order);
            seen.assign(n, false);
            int count = 0;
            for (int k = n - 1; k >= 0; k--) {      // on the reversed graph, each search from the latest finisher is one SCC
                int u = order[k];
                if (seen[u]) continue;
                count++;
                collect(u, rev, seen);
            }
            return count;
        }
    
        void finish(int u, vector<vector<int>>& adj, vector<bool>& seen, vector<int>& order) {
            seen[u] = true;
            for (int v : adj[u]) if (!seen[v]) finish(v, adj, seen, order);
            order.push_back(u);
        }
    
        void collect(int u, vector<vector<int>>& rev, vector<bool>& seen) {
            seen[u] = true;
            for (int v : rev[u]) if (!seen[v]) collect(v, rev, seen);
        }
    };

    Python

    class Solution:
        def kosaraju(self, n: int, edges: list[list[int]]) -> int:
            adj, rev = [[] for _ in range(n)], [[] for _ in range(n)]
            for u, v in edges:
                adj[u].append(v)
                rev[v].append(u)
            order, seen = [], [False] * n           # vertices by finishing time
    
            def finish(u):
                seen[u] = True
                for v in adj[u]:
                    if not seen[v]:
                        finish(v)
                order.append(u)
    
            def collect(u):
                seen[u] = True
                for v in rev[u]:
                    if not seen[v]:
                        collect(v)
    
            for i in range(n):
                if not seen[i]:
                    finish(i)
            seen, count = [False] * n, 0
            for u in reversed(order):               # on the reversed graph, each search from the latest finisher is one SCC
                if not seen[u]:
                    count += 1
                    collect(u)
            return count

    Common mistakes

    • Running the second pass on the original graph.
    • Processing vertices in increasing order in the second pass.

    Similar problems