Sub topic 14
Tarjan vs. Kosaraju: Memory, Passes, and Output Order
Both algorithms find the same strongly connected components (SCCs) in O(V + E) time, so asymptotic analysis does not tell you which one to use. The real differences are in how many times each algorithm reads the graph, how much extra memory it allocates, what kind of graph access it needs, and the order in which it reports components. This chapter compares the two on each of those points and ends with criteria for choosing.
This chapter assumes you have read the earlier chapters on Kosaraju's algorithm, Tarjan's algorithm, the condensation DAG, and the O(V + E) analysis. It also assumes you can read the Python implementations given there.
Passes over the graph
Kosaraju's algorithm reads every edge three times:
- The first DFS on the original graph records the finish order.
- Building the transpose
radjreads every edge once more and writes a reversed copy. - The second DFS on the transpose reads every reversed edge.
Tarjan's algorithm reads every edge exactly once, during its single DFS. Each edge v -> w falls into one of three cases: w is unvisited (recurse), w is on the stack (update low[v]), or w is finished and already assigned to a component (ignore it).
Both counts are O(V + E), but the constant factors differ. On large graphs that do not fit in cache, each pass over the edge array means memory traffic, so Tarjan's single pass usually runs faster in practice. Its inner loop has more branching and bookkeeping per edge, though, so on small graphs the gap is narrow. If speed matters, measure on your own data.
Memory use
The table below lists what each implementation from the earlier chapters allocates on top of the input adjacency list.
| Structure | Kosaraju | Tarjan |
|---|---|---|
| Per-vertex arrays | `visited`, `comp` (2 arrays) | `index`, `low`, `on_stack` (3 arrays) |
| Vertex sequence | `order` (up to V entries) | `stack` (up to V entries) |
| Edge storage | `radj`, a full transpose (E entries plus V lists) | none |
| Output | `comp` labels | `sccs` lists (V entries total) |
| Recursion depth, worst case | O(V) in each of two DFS passes | O(V) in one DFS pass |
The transpose is the deciding entry. Tarjan's extra memory is O(V) no matter how dense the graph is. Kosaraju's extra memory is O(V + E), because it copies every edge. On a graph with 10 million vertices and 200 million edges, that copy is far larger than all the per-vertex arrays combined.
Two situations remove this cost:
- The reverse edges already exist. Many graph stores keep in-edge lists alongside out-edge lists, for example compressed sparse row (CSR) and compressed sparse column (CSC) pairs, or databases that index both edge directions. Kosaraju can then walk the in-edges directly and skip building
radj. - The graph is small. For a few thousand edges, the copy costs nothing worth measuring.
Tarjan's per-vertex overhead can also be reduced. Pearce's variant (2016) merges index, low, and the component label into one integer array and replaces on_stack with a single bit per vertex. It produces the same output with roughly one word per vertex.
Graph access requirements
Tarjan needs only one operation: "give me the out-neighbors of v." Kosaraju also needs "give me the in-neighbors of v," either from storage or by building the transpose up front, which requires enumerating all edges first.
This matters for implicit graphs, where neighbors are generated on demand instead of stored. Examples include the state space of a model checker, the configurations of a puzzle, and a call graph discovered while parsing. In those cases you cannot reverse an edge you have not generated yet, and you may not want to generate the whole graph before starting. Tarjan explores from a start state and emits components as it goes. Kosaraju has to materialize everything first.
Output order
Both algorithms number components in an order that is consistent with the condensation DAG, but the orders run in opposite directions:
- Kosaraju assigns component 0 first in the second pass. Component 0 is a source of the condensation, and every condensation edge goes from a lower number to a higher one. The labels are in topological order.
- Tarjan emits a component when its root finishes. That happens only after every component reachable from it has already been emitted, so the first component emitted is a sink. The output is in reverse topological order.
The shared example graph from earlier chapters shows both orders:
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
# kosaraju(8, adj) -> [1, 1, 1, 2, 2, 2, 0, 0]
# component 0 = {6, 7} (source)
# component 1 = {0, 1, 2} (source)
# component 2 = {3, 4, 5} (sink)
# tarjan(8, adj) -> [[5, 4, 3], [2, 1, 0], [7, 6]]
# first emitted = {3, 4, 5} (sink)Which direction is useful depends on the task:
- Bottom-up processing, such as computing per-component results from dependencies (build order, transitive closure sizes, dynamic programming over the DAG), wants sinks first. Tarjan's output is ready to use as is.
- Top-down processing, such as propagating values from sources or scheduling work that unlocks later work, wants sources first. Kosaraju's labels are ready to use as is.
Converting between the two is cheap: reverse Tarjan's list, or relabel component i as k - 1 - i. The bug to watch for is code that compares component numbers. 2-SAT is the standard case: its assignment rule compares comp[x] with comp[not x], and that comparison flips depending on which algorithm produced the numbers. The next chapter covers it in detail.
Checking that the two agree
When you swap one algorithm for the other, or write an iterative version, test it against a reference implementation on random graphs. The harness below converts Tarjan's output into Kosaraju-style labels, checks that both algorithms give the same partition, and confirms that both orders respect the condensation edges. Save the kosaraju, tarjan, and condensation functions from the earlier chapters as scc.py in the same directory before running it.
import random
import sys
from scc import kosaraju, tarjan, condensation
sys.setrecursionlimit(10000)
def tarjan_labels(n, adj):
"""Tarjan output as labels in topological order (sources first)."""
sccs = tarjan(n, adj)
k = len(sccs)
comp = [-1] * n
for i, members in enumerate(sccs):
for v in members:
comp[v] = k - 1 - i # reverse the emission order
return comp
def same_partition(a, b):
"""True if two labelings group vertices identically."""
mapping = {}
for x, y in zip(a, b):
if mapping.setdefault(x, y) != y:
return False
return len(set(mapping.values())) == len(mapping)
def is_topological(n, adj, comp):
"""True if every condensation edge goes from a lower label to a higher one."""
dag = condensation(n, adj, comp)
return all(c < d for c, succs in enumerate(dag) for d in succs)
random.seed(1)
for trial in range(500):
n = random.randint(1, 40)
m = random.randint(0, 3 * n)
adj = [[] for _ in range(n)]
for _ in range(m):
adj[random.randrange(n)].append(random.randrange(n))
k_comp = kosaraju(n, adj)
t_comp = tarjan_labels(n, adj)
assert same_partition(k_comp, t_comp), adj
assert is_topological(n, adj, k_comp), adj
assert is_topological(n, adj, t_comp), adj
print("all trials passed")The two labelings can differ when the condensation has more than one valid topological order. In the example graph, {0,1,2} and {6,7} are both sources, and nothing forces one ahead of the other. That is why the harness checks for the same partition and a valid order instead of identical labels.
Recursion and iterative versions
Both recursive implementations can reach depth V. A path of 100,000 vertices overflows Python's default limit of 1000 in either one. Kosaraju is the easier of the two to make iterative:
- The first pass needs a post-order DFS, which takes an explicit stack of (vertex, edge position) frames.
- The second pass can be a plain stack-based or queue-based traversal, because order inside a component does not matter.
The iterative version of Tarjan is harder to get right. When a child frame finishes, the parent's low must be updated from the child's low. The iterative chapter's code does this right after a frame is exhausted (low[parent] = min(low[parent], low[v])). Forgetting that update is the most common bug in hand-written iterative Tarjan. It merges or splits components only on some graphs, so you need a random test like the one above to catch it.
Choosing between them
| Criterion | Prefer |
|---|---|
| Only out-neighbors available | Tarjan |
| Extra memory must stay O(V) | Tarjan |
| Reverse edges already stored | Kosaraju is competitive |
| Easiest to explain, audit, or make iterative | Kosaraju |
| Need sinks first (bottom-up) | Tarjan |
| Need sources first (top-down) | Kosaraju |
| Components wanted as they are found | Tarjan |
Exercise
A graph has 5 million vertices and 80 million edges, stored as out-edge lists using 4-byte integers. Roughly how much extra edge memory does Kosaraju's transpose need, and how does that compare with Tarjan's three per-vertex arrays at 4 bytes each?
Show answer
The transpose stores 80 million edge entries, about 320 MB, plus list overhead for 5 million vertices. Tarjan's index, low, and onstack arrays take about 3 × 5 million × 4 bytes = 60 MB even when onstack is stored as full integers, and its stack holds at most 5 million more entries. Kosaraju's transpose alone is more than five times Tarjan's per-vertex arrays.
Exercise
Your code takes SCC labels from Kosaraju's algorithm and processes components in increasing label order so that each component's dependencies (its successors in the condensation) are already computed. A colleague swaps in Tarjan and numbers components by emission order (first emitted = 0). Does the processing still work?
Show answer
It works by accident with Tarjan and fails with the original Kosaraju setup. Dependencies are successors, so they must be processed before their predecessors, which means sinks first. Tarjan's emission order is sinks first, so processing labels 0, 1, 2, ... is correct. Kosaraju's increasing labels are sources first, so the original code processed each component before its dependencies. With Kosaraju it needed to iterate labels in decreasing order.
Exercise
Why can the second pass of Kosaraju's algorithm use BFS, while the first pass cannot?
Show answer
The second pass only has to collect all unassigned vertices reachable from the start vertex in the transpose. Processing start vertices in decreasing finish order already guarantees that this set is exactly one SCC, and any complete traversal finds the same set. The first pass needs DFS finish times, a post-order property that BFS does not produce.