Sub topic 6
Reversing Every Edge: The Transpose Graph
This chapter assumes you can read Python, represent a directed graph as an adjacency list, and follow a depth-first search. It also builds on the two ideas covered just before it: strongly connected components (SCCs) and the condensation DAG. The transpose is a simple object. Kosaraju's algorithm depends on one of its properties, though, and building it correctly has a few traps.
Definition
The transpose of a directed graph G = (V, E), written Gᵀ, has the same vertices and has every edge reversed:
- Gᵀ = (V, Eᵀ), where Eᵀ = { (v, u) : (u, v) ∈ E }.
When G is stored as an adjacency matrix A, the transpose's matrix is the matrix transpose Aᵀ. That is where the name comes from. When G is stored as an adjacency list, adj[u] lists u's out-neighbors. In the transpose, radj[v] lists v's in-neighbors in G.
The rest of this chapter uses the running example graph:
| Vertex | Out-neighbors in G | Out-neighbors in Gᵀ |
|---|---|---|
| 0 | 1 | 2 |
| 1 | 2 | 0 |
| 2 | 0, 3 | 1 |
| 3 | 4 | 2, 5 |
| 4 | 5 | 3 |
| 5 | 3 | 4, 6 |
| 6 | 5, 7 | 7 |
| 7 | 6 | 6 |
The Key Property: Reachability Reverses
Claim. Vertex u reaches v in G exactly when v reaches u in Gᵀ.
Proof. Take a path u = x₀ → x₁ → … → xₖ = v in G. Each edge (xᵢ, xᵢ₊₁) appears in Gᵀ as (xᵢ₊₁, xᵢ), so xₖ → xₖ₋₁ → … → x₀ is a path from v to u in Gᵀ. For the converse, apply the same argument to Gᵀ and use the fact that (Gᵀ)ᵀ = G. ∎
Two consequences follow, and Kosaraju's algorithm relies on both.
- G and Gᵀ have exactly the same SCCs. u and v share a component when u reaches v and v reaches u. Reversing edges turns each of those two facts into the other, so the condition does not change.
- The condensation of Gᵀ is the transpose of the condensation of G. An edge between two components flips along with the edges it was built from. Source components (no incoming component edges) become sink components (no outgoing ones), and sinks become sources.
In the example, the condensation of G has component edges {0,1,2} → {3,4,5} and {6,7} → {3,4,5}. The component {3,4,5} is a sink in G and a source in Gᵀ. In Gᵀ, a DFS started inside {0,1,2} cannot leave that component, because no edge of Gᵀ leaves it. The next chapter shows how Kosaraju's algorithm uses this to make each DFS tree exactly one SCC.
Building the Transpose from an Adjacency List
The standard construction visits every edge once and appends it, reversed, to the target's list:
def transpose(n, adj):
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
return radj
def reachable(adj, s):
seen = {s}
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if v not in seen:
seen.add(v)
stack.append(v)
return seen
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
n = len(adj)
radj = transpose(n, adj)
print(radj) # [[2], [0], [1], [2, 5], [3], [4, 6], [7], [6]]
# Check the reachability property for every pair of vertices.
reach_g = [reachable(adj, u) for u in range(n)]
reach_t = [reachable(radj, u) for u in range(n)]
ok = all((v in reach_g[u]) == (u in reach_t[v])
for u in range(n) for v in range(n))
print(ok) # True
print(transpose(n, radj) == adj) # TrueThe construction takes O(V + E) time. Allocating the empty lists costs O(V), and the double loop handles each edge exactly once. The transpose uses another O(V + E) of memory, so you now hold two copies of the edge set.
Neighbor order
Because the outer loop runs over u in increasing order, every list radj[v] comes out sorted by source vertex. That makes the output deterministic. It also explains why transposing twice returned exactly adj above: the original lists happened to be sorted. In general, transpose(transpose(adj)) has the same multiset of edges as adj, but each list may come back in a different order. SCC algorithms do not depend on neighbor order for correctness. Order does change which DFS tree is found first, and therefore how components are numbered.
Self-loops, parallel edges, isolated vertices
- A self-loop (u, u) maps to itself and stays in
radj[u]. - Parallel edges are kept. If
adj[u]lists v twice,radj[v]lists u twice. This is harmless, since a DFS skips the duplicate once v is visited. - A vertex with no edges gets an empty list in both graphs. It is a single-vertex SCC.
Common Errors
Aliased lists
n = 3
adj = [[1], [2], [0]]
bad = [[]] * n # three references to ONE list
for u in range(n):
for v in adj[u]:
bad[v].append(u)
print(bad) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
good = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
good[v].append(u)
print(good) # [[2], [0], [1]][[]] * n copies the reference, not the list, so every vertex shares one list. The resulting graph is wrong, and no error is raised. Always build the outer list with a comprehension.
Missing vertices in dictionary graphs
Graphs stored as dict often have keys only for vertices with outgoing edges. If you build the transpose by looping over keys, the transpose may lack keys for vertices that had no in-edges, and a later radj[v] raises KeyError. Declare every vertex explicitly:
from collections import defaultdict
def transpose_dict(graph):
vertices = set(graph)
for targets in graph.values():
vertices.update(targets)
radj = {v: [] for v in vertices}
for u, targets in graph.items():
for v in targets:
radj[v].append(u)
return radj
deps = {"app": ["lib", "log"], "lib": ["log"]}
print(transpose_dict(deps))
# keys: app, lib, log (set order may vary)
# {'app': [], 'lib': ['app'], 'log': ['app', 'lib']}Here "log" never appears as a key in deps, but it must appear in the transpose. Iterating over the original keys alone would also skip it as a DFS start vertex in Gᵀ.
Reversing in place
Code that tries to flip edges inside adj as it iterates usually reverses some edges twice or loses some. Build a new structure instead. If memory is tight, use one of the representations below.
Representation Choices
| Representation | How to get Gᵀ | Extra memory | Notes |
|---|---|---|---|
| Adjacency list | Rebuild as shown | O(V + E) | Simplest; standard for Kosaraju |
| Edge list | Swap each pair: `[(v, u) for u, v in edges]` | O(E) | Then group by source if you need lists |
| Adjacency matrix | Read `A[v][u]` instead of `A[u][v]` | None | Costs O(V²) to scan, too slow for sparse graphs |
| In- and out-lists stored together | Already present | Built at load time | Common in graph libraries; lets you walk either direction |
| Compressed sparse row (CSR) | Counting sort on targets | O(V + E) in flat arrays | Cache-friendly; good for millions of edges |
The CSR version stores all in-neighbors in one flat array plus an offset array. In-neighbors of v sit in targets[start[v]:start[v + 1]]:
def transpose_csr(n, adj):
start = [0] * (n + 1)
for u in range(n):
for v in adj[u]:
start[v + 1] += 1 # count in-degree of v
for i in range(n):
start[i + 1] += start[i] # prefix sums give offsets
pos = start[:n] # next free slot for each v
targets = [0] * start[n]
for u in range(n):
for v in adj[u]:
targets[pos[v]] = u
pos[v] += 1
return start, targets
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
start, targets = transpose_csr(len(adj), adj)
print(start) # [0, 1, 2, 3, 5, 6, 8, 9, 10]
print(targets) # [2, 0, 1, 2, 5, 3, 4, 6, 7, 6]
print(targets[start[5]:start[6]]) # [4, 6]This version also runs in O(V + E). It replaces V small Python lists with two arrays, which matters when the graph is large.
Exercises
Exercise
A directed graph has edges 0→1, 1→2, 2→1, 2→3, 3→3. Write the adjacency list of its transpose, list the SCCs of both graphs, and name the source and sink components of each condensation.
Show answer
Transpose: 0: [], 1: [0, 2], 2: [1], 3: [2, 3]. Both graphs have SCCs {0}, {1,2}, {3}. In G the condensation is {0} → {1,2} → {3}, so {0} is the source and {3} the sink. In the transpose the condensation is {3} → {1,2} → {0}, so {3} is the source and {0} the sink. The self-loop on 3 stays a self-loop.
Exercise
A teammate builds a transpose with radj = {u: [] for u in graph} followed by the usual double loop, where graph is a dict. It works on some inputs and raises KeyError on others. What inputs trigger the error, and what is the fix?
Show answer
The error appears whenever some vertex occurs only as an edge target and never as a key, for example a dependency that depends on nothing. Then radj[v].append(u) looks up a missing key. The fix is to collect every vertex, both keys and all targets, before creating the empty lists, as transpose_dict does. Using a defaultdict(list) avoids the crash, but vertices with no in-edges still end up missing from the transpose's keys, so any loop over its keys skips them.
Exercise
Prove that if C is a sink component in the condensation of G, then no edge of the transpose enters C from another component.
Show answer
Suppose an edge of the transpose goes from x to y, with x outside C and y inside C. Then G has the edge from y to x, which leaves C for a different component. That gives the condensation of G an outgoing edge from C, which contradicts C being a sink. So in the transpose, a sink of G's condensation has no incoming component edges. It is a source.