Kosaraju's Algorithm for Strongly Connected Components

Find strongly connected components using the two-pass Kosaraju's algorithm with graph transpose and DFS finishing times.

published: reading time: 16 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

Kosaraju's algorithm finds strongly connected components with two depth-first passes: record finish order in the original graph, then search the transpose in decreasing finish time. For the condensation DAG, a source component in the original graph is a sink in the transpose, so each second-pass traversal stays within one SCC. This guide proves that ordering, works through a four-vertex graph and an isolated vertex, and compares the memory and implementation trade-offs with Tarjan's algorithm.

Kosaraju’s Algorithm for Strongly Connected Components

Kosaraju’s algorithm finds strongly connected components (SCCs) with two depth-first searches. The first records vertices in finishing order on the original graph. The second searches the transposed graph in decreasing finish time. The transpose takes O(V + E) extra space, and recursive DFS can hit the language’s call-stack limit on a long path.

Introduction

For a directed graph G, collapse each SCC into one vertex to form the condensation DAG. Here, a source has no incoming edges from other SCCs, and a sink has no outgoing edges to other SCCs. If the DAG has an edge A → B, A is upstream of B in G; reversing every edge swaps source and sink. The second pass relies on this orientation and on the first pass’s finish times.

This article proves the ordering, traces a small graph by hand, and compares Kosaraju’s storage and recursion trade-offs with Tarjan’s algorithm.

When to Use

Kosaraju’s is a reasonable choice when the graph and its transpose fit in memory and a two-pass implementation is easier to review for your team. If the transpose is already available, constructing it adds little work. Tarjan’s algorithm avoids storing a second adjacency list, which can matter when memory is tight.

When Not to Use

The transpose requires another O(V + E) adjacency structure, so Tarjan’s may fit better if that memory is unavailable. Both algorithms are O(V + E); which is faster in practice depends on the graph representation, memory layout, implementation, and workload. Benchmark the implementation you plan to use.

The recursive Python implementation below can raise RecursionError on a deep graph. Python’s recursion limit is runtime-configurable, so do not assume a fixed safe vertex count. Use an explicit-stack DFS for inputs with long paths, or use a tested iterative implementation.

Architecture: Two-Pass Approach

graph LR
    A[Original Graph] --> B[Pass 1: DFS, record finishing times]
    B --> C[Sort vertices by finishing time descending]
    C --> D[Transpose Graph]
    D --> E[Pass 2: DFS in sorted order, on transpose]
    E --> F[SCCs identified]

Pass 1: Run DFS on original graph, pushing vertices onto a stack as they finish (post-order).

Pass 2: Reverse the graph, then run DFS popping vertices from the stack (which gives reverse finishing order), extracting each DFS tree as one SCC.

Why the ordering works

For an SCC C, let f(C) be the greatest finishing time of any vertex in C during pass 1. Consider an edge A → B between different SCCs in G. If DFS reaches A before B, strong connectivity within A lets the search reach the edge to B; the search then finishes B before it finishes the active DFS in A, so f(A) > f(B). If B has already finished before DFS first reaches A, then A receives a later finishing time, again giving f(A) > f(B). Thus decreasing finish time visits SCCs in source-to-sink order in G’s condensation DAG.

In the transpose Gᵀ, each source SCC of G becomes a sink. The first unprocessed SCC in decreasing finish order is a source among the remaining SCCs in G, so it is a sink among the remaining SCCs in Gᵀ. A DFS started there cannot reach another unvisited SCC because that sink has no outgoing edges to other remaining components. It does reach every vertex in its own SCC, since vertices within an SCC are mutually reachable. That second-pass DFS tree is exactly one SCC. Mark it visited and repeat on the remaining graph; the same reasoning applies at each step.

Four-vertex walkthrough

Use vertices 0, 1, 2, 3 and edges 0 → 1, 1 → 0, 1 → 2, 2 → 3, and 3 → 2. The first two vertices form SCC A; the last two form SCC B. The condensation DAG has one edge, A → B.

If pass 1 starts at 0 and explores neighbors in the listed order, its finish order is [3, 2, 1, 0]. Pass 2 processes [0, 1, 2, 3] on the transpose. Starting at 0 reaches 1, but cannot cross into B, so the first component is {0, 1}. The next unvisited vertex, 2, reaches 3 and gives {2, 3}.

Now add isolated vertex 4. It has no path to or from any other vertex, so it is its own SCC {4}. Its position in the returned list depends on the vertex iteration order; the SCC membership does not.

Implementation

def kosaraju_scc(vertices, edges):
    """
    Find all strongly connected components using Kosaraju's algorithm.
    Time: O(V + E), Space: O(V + E)
    """
    # Build adjacency lists
    graph = build_graph(vertices, edges)
    transpose = build_transpose(vertices, edges)

    # Pass 1: DFS to compute finishing times
    visited = set()
    finishing_order = []

    def dfs(v):
        visited.add(v)
        for neighbor in graph.get(v, []):
            if neighbor not in visited:
                dfs(neighbor)
        finishing_order.append(v)

    for v in vertices:
        if v not in visited:
            dfs(v)

    # Pass 2: DFS on transpose in reverse finishing order
    visited.clear()
    sccs = []

    def dfs_transpose(v, component):
        visited.add(v)
        component.append(v)
        for neighbor in transpose.get(v, []):
            if neighbor not in visited:
                dfs_transpose(neighbor, component)

    # Process in reverse finishing order
    for v in reversed(finishing_order):
        if v not in visited:
            component = []
            dfs_transpose(v, component)
            sccs.append(component[:])

    return sccs


def build_graph(vertices, edges):
    """Build adjacency list from edge list."""
    graph = {v: [] for v in vertices}
    for src, dst in edges:
        graph[src].append(dst)
    return graph


def build_transpose(vertices, edges):
    """Build transpose graph (reverse all edges)."""
    transpose = {v: [] for v in vertices}
    for src, dst in edges:
        transpose[dst].append(src)
    return transpose

These assertions check both examples without depending on the order of components in the returned list:

def component_set(vertices, edges):
    return {frozenset(component) for component in kosaraju_scc(vertices, edges)}


four_vertex_edges = [(0, 1), (1, 0), (1, 2), (2, 3), (3, 2)]
assert component_set([0, 1, 2, 3], four_vertex_edges) == {
    frozenset({0, 1}),
    frozenset({2, 3}),
}
assert component_set([0, 1, 2, 3, 4], four_vertex_edges) == {
    frozenset({0, 1}),
    frozenset({2, 3}),
    frozenset({4}),
}

Common Implementation Mistakes

Failure Cause Mitigation
Wrong finishing order Using pre-order instead of post-order Append after exploring all neighbors
Incorrect transpose Forgetting to reverse direction of ALL edges Verify with simple cycle graph
Processing order Starting second pass without clearing visited Reset visited before pass 2
Stack overflow Deep recursion on large graphs Use iterative DFS with explicit stack

Trade-off Analysis: Kosaraju vs. Tarjan

Aspect Kosaraju’s Algorithm Tarjan’s Algorithm
Passes Two DFS passes One DFS pass
Additional storage O(V + E) for the transpose, plus O(V) traversal state O(V) traversal state beyond the input graph
Main invariant Finish order in G, then DFS on Gᵀ Low-link values and the active-vertex stack
SCC output order Source-to-sink in G’s condensation DAG; incomparable SCCs may vary Depends on how the implementation returns components
Practical performance Depends on representation, memory layout, implementation, workload Depends on representation, memory layout, implementation, workload
Teaching/learning Two passes may be easier to trace when teaching DFS Useful for studying low-link values and stack invariants

Kosaraju can fit well when:

  • Teaching graph algorithms or writing tutorial content
  • You want SCCs emitted in a source-to-sink order of G’s condensation DAG
  • Memory is not a primary constraint
  • Code clarity matters more than micro-optimization

Tarjan can fit well when:

  • Production systems with memory constraints
  • Your graph and its transpose do not fit the available memory
  • You need a single-pass solution
  • You have measured that its implementation fits the workload better

Common Pitfalls / Anti-Patterns

  1. Confusing pre-order with post-order — Finishing time should be recorded AFTER recursion returns, not before
  2. Forgetting to reset visited — Pass 2 needs fresh visited set
  3. Graph with self-loops — Self-loop makes vertex trivially SCC; transpose handles correctly
  4. Disconnected graphs — Ensure all vertices visited in pass 1, handle isolated vertices

Quick Recap Checklist

  • Pass 1 records finishing times correctly (post-order)
  • Transpose graph built by reversing all edges
  • Pass 2 processes in reverse finishing order
  • Each DFS tree in pass 2 is one SCC
  • Test with: self-loop, isolated vertex, linear chain, bidirectional cycle

Interview Questions

1. Why does processing vertices in reverse finishing time find all SCCs?

In the condensation DAG of the original graph G, the SCC with the greatest finishing time is a source (no incoming edges from other SCCs). Transposing G reverses those edges, so that component is a sink in Gᵀ. A DFS from that sink can reach every vertex in its own SCC, but no other unvisited SCC. Mark it visited and repeat on the remaining graph.

2. Why is two passes sufficient?

Collapse each SCC into one vertex; the resulting condensation graph is a DAG. For every edge A → B between different SCCs, the maximum finishing time in A is greater than the maximum finishing time in B. Thus decreasing finish time orders SCCs source-to-sink in G. In Gᵀ, the first remaining SCC is a sink, so its traversal cannot cross into another unvisited SCC. Each DFS tree in pass 2 is exactly one component.

3. Which is better: Kosaraju's or Tarjan's?

Neither is universally better. Both run in O(V + E). Kosaraju's stores the transpose and has two clear passes; Tarjan's avoids that second adjacency structure but tracks low-link state. Choose based on available memory, the graph representation, implementation constraints, and measurements on the workload.

4. What is the time and space complexity of Kosaraju's algorithm?

Both passes are standard DFS traversals:

  • Time complexity: O(V + E) — each vertex is processed and each adjacency list is scanned once in each pass
  • Space complexity: O(V + E) — adjacency list, transpose graph, visited set, and finishing order stack
  • The transpose graph doubles the space compared to Tarjan's, but total space is still linear in the input size
5. How does Kosaraju's algorithm handle graphs with self-loops?

Self-loops are handled naturally. A vertex with a self-loop trivially forms a strongly connected component (an SCC of size 1). The transpose graph preserves the self-loop, so the DFS in pass 2 will correctly include it. No special handling is needed — both the original and transpose graphs maintain the self-loop edge.

6. What happens when you run Kosaraju's algorithm on a DAG?

On a DAG, every vertex is its own SCC because no two distinct vertices can reach each other in both directions. Kosaraju's emits these singleton components in a topological order of the original DAG; among incomparable vertices, the order depends on traversal order.

7. Can you explain the connection between Kosaraju's algorithm and the condensation graph?

The condensation graph collapses each SCC into one vertex and keeps edges between components. It is always a DAG. In the original graph's condensation DAG, decreasing maximum finish time gives a source-to-sink topological order. The second pass runs on the transpose, where those sources are sinks; this prevents a traversal from reaching another unvisited SCC.

8. How would you implement Kosaraju's algorithm iteratively to avoid stack overflow on large graphs?

Replace the recursive DFS with an explicit stack:

  • Pass 1: Use a manual stack of (vertex, iterator_state) pairs. Push vertices, track visited, and record finishing time after all neighbors are processed (simulating post-order).
  • Pass 2: Same approach on the transpose graph. Use the explicit stack to traverse, collecting vertices into the current component.
  • This moves traversal state to an explicit heap-allocated stack; the needed stack size still depends on the graph.
9. Why do we use a stack data structure for finishing times rather than a queue or list?

Append each vertex after all its neighbors finish. The last appended vertex has the greatest finish time, so iterating over the list in reverse starts with the source SCC of G (a sink SCC in Gᵀ). A Python list is enough; the algorithm does not require a special stack type.

10. What is the relationship between Kosaraju's algorithm and graph strongly connected components in social network analysis?

In a directed follow graph, an SCC is a group where each account can reach every other account by following directed paths. A one-way follow from A to B does not place the two accounts in the same SCC. The same definition applies to any directed graph.

11. How does Kosaraju's algorithm behave on a completely disconnected graph?

If the graph has no edges, each vertex is an isolated SCC. Pass 1 records each vertex when its DFS finishes; pass 2 returns one singleton component per vertex. A disconnected graph may still contain cycles within its separate parts, and those cycles can form larger SCCs. The running time remains O(V + E).

12. Can Kosaraju's algorithm be modified to return SCCs in topological order of the condensation graph?

With pass 1 on G and pass 2 on Gᵀ in decreasing finish time, SCCs are emitted in a source-to-sink topological order of G's condensation DAG. To get sink-to-source order, reverse the list of components after the algorithm returns. Within a component, vertex order is not significant.

13. What happens to the finishing times if the graph contains a cycle within a single SCC?

Finishing times within an SCC depend on the DFS tree and neighbor order. The useful property concerns SCCs as a whole: for each edge A → B between different SCCs, the maximum finish time in A is greater than the maximum in B. Individual vertices from A and B need not appear as separate blocks in the finish order.

14. How does the algorithm handle multi-edges between the same pair of vertices?

Multiple edges between the same vertices (parallel edges) are treated identically to single edges in DFS—both adjacency list and transpose representation will contain duplicates. The algorithm still works correctly; DFS visits each neighbor regardless of duplicates, so the extra edges don't change the SCC membership. However, if performance matters, you can deduplicate edges during graph construction, as they don't affect connectivity properties.

15. What is the role of the transpose graph in ensuring correctness?

Reversing every edge makes each source SCC in G a sink SCC in Gᵀ. Because a sink has no outgoing edges to other components, a second-pass DFS cannot leave it for another unvisited SCC. This is why the transpose and decreasing finish order work together.

16. Compare the space complexity of Kosaraju's vs. Tarjan's algorithm and explain why the difference exists.

Both algorithms need the input graph, which takes O(V + E) space as an adjacency list. Kosaraju additionally stores the transpose, also O(V + E), plus O(V) finish-order, visited, and result data. Tarjan uses O(V) extra state for its index, low-link, and stack data. The transpose is the main extra-memory difference; actual memory use also depends on the representation and runtime.

17. In what order does Kosaraju's algorithm discover SCCs?

With pass 1 on G and pass 2 on Gᵀ, the standard version emits SCCs in a source-to-sink topological order of G's condensation DAG. The relative order of incomparable SCCs can vary with traversal order. Reverse the returned component list if you need sink-to-source order; keep the second pass in decreasing finish time for correctness.

18. How would you verify that Kosaraju's algorithm is implemented correctly without a ground-truth dataset?

Test a self-loop, a directed chain, a bidirectional cycle, two disconnected cycles, and a graph with an isolated vertex. Compare component membership as sets instead of relying on return order. For a stronger check, verify that vertices within each reported SCC are mutually reachable and that no two reported components can be merged.

19. What does vertex ordering affect in Kosaraju's algorithm?

The order of vertices and neighbors can change the finish-time sequence and the order of incomparable SCCs in the result. It does not change the O(V + E) bound. Actual runtime depends on how the graph is represented and laid out in memory, so measure with the representation and workload you plan to use.

20. How does Kosaraju's algorithm relate to finding the minimum path cover in a DAG?

SCC decomposition does not by itself solve a minimum path cover problem. For a DAG, minimum path cover can be reduced to bipartite matching; each SCC is then a singleton. For a graph with cycles, the condensation DAG summarizes reachability between SCCs, but a path cover on that DAG does not automatically translate into a path cover of the original vertices. The translation depends on the path-cover definition and the graph's structure.

Further Reading

  • Original Paper: S. Rao Kosaraju’s 1978 technical report on finding strongly connected components using two DFS passes
  • Tarjan’s Algorithm: Robert Tarjan’s linear-time SCC algorithm using low-link values; it avoids building a transpose
  • Textbook References:
    • CLRS (Introduction to Algorithms) — Chapter 22: Elementary Graph Algorithms
    • Robert Sedgewick & Kevin Wayne, Algorithms — Graph processing chapter
  • Online Resources:
  • Related Blog Posts:

Conclusion

Kosaraju’s algorithm finds SCCs with two DFS passes. Record post-order finishing times in G, then search Gᵀ in decreasing finish time. On the condensation DAG, a source in G is a sink in Gᵀ; that is why each second-pass DFS tree contains exactly one SCC. The main implementation choice is whether the extra transpose fits in memory and whether recursion is safe for the graph’s depth.

Category

Related Posts

Tarjan's Strongly Connected Components

Find strongly connected components in directed graphs using DFS-based Tarjan's algorithm with lowlink values.

#tarjan-scc #graph-algorithms #strongly-connected-components

Articulation Points & Bridges in Graphs

Learn how DFS low-link values identify articulation points and bridges in undirected graphs, including root cases and disconnected components.

#articulation-points #bridges #graph-algorithms

Bellman-Ford Algorithm: Shortest Paths with Negative Weights

Learn the Bellman-Ford algorithm for single-source shortest paths including negative edge weights and negative cycle detection.

#bellman-ford #shortest-path #graph-algorithms