Sub topic 12
Linear Time: O(V + E) Analysis
This chapter assumes you already know Big-O notation, how adjacency lists store a directed graph, and the Kosaraju and Tarjan implementations from the previous chapters. Here, V is the number of vertices and E is the number of edges.
The Counting Argument
Both algorithms are built from depth-first search, so they share the same core argument. Every vertex is marked when DFS first reaches it, and DFS never starts from a marked vertex again. DFS scans a vertex's adjacency list only during that single visit. Across the whole run, it therefore looks at every edge exactly once. Each vertex visit and each edge check costs O(1), so one full DFS costs O(V + E).
The algorithms differ only in what else they do around that DFS.
Kosaraju's Cost, Pass by Pass
| Step | Time | Extra space |
|---|---|---|
| First DFS, record finish order | O(V + E) | O(V) for `visited` and `order` |
| Build `radj` | O(V + E) | O(V + E) for the reversed edges |
| Second DFS in decreasing finish order | O(V + E) | O(V) for `comp` |
Three linear passes add up to a linear total. The largest extra cost is memory: the transpose copies every edge.
Tarjan's Cost
Tarjan's algorithm runs a single DFS. Its extra work has these bounds:
- Each vertex is pushed onto the component stack once, when it is discovered.
- Each vertex is popped once, when its component is emitted.
- Each
low[v] = min(...)update is O(1) and happens at most once per edge.
That makes the total O(V + E) time. The extra space is O(V): index, low, on_stack, and the stack itself.
Checking the Bound by Counting
The code below adds counters to Tarjan's algorithm. The edge checks should equal E, and the pushes and pops should each equal V.
def tarjan_counted(n, adj):
index = [None] * n
low = [0] * n
on_stack = [False] * n
stack = []
ops = {"edge_checks": 0, "pushes": 0, "pops": 0}
counter = 0
def strongconnect(v):
nonlocal counter
index[v] = low[v] = counter
counter += 1
stack.append(v)
on_stack[v] = True
ops["pushes"] += 1
for w in adj[v]:
ops["edge_checks"] += 1
if index[w] is None:
strongconnect(w)
low[v] = min(low[v], low[w])
elif on_stack[w]:
low[v] = min(low[v], index[w])
if low[v] == index[v]:
while True:
w = stack.pop()
on_stack[w] = False
ops["pops"] += 1
if w == v:
break
for v in range(n):
if index[v] is None:
strongconnect(v)
return ops
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
E = sum(len(a) for a in adj)
print("V =", len(adj), "E =", E) # V = 8 E = 10
print(tarjan_counted(len(adj), adj)) # {'edge_checks': 10, 'pushes': 8, 'pops': 8}Common Errors That Break Linearity
- Adjacency matrix input. Scanning one row of a matrix costs O(V) even when the vertex has few edges, so the total becomes O(V²). Convert the matrix to adjacency lists first.
- Rebuilding the transpose inside a loop. Build
radjonce, before the second pass. - Sorting by finish time. Kosaraju's algorithm does not need a sort. Appending each vertex to
orderwhen it finishes already gives the right order, andreversed(order)costs O(V). A comparison sort adds O(V log V). - Recursion depth. The recursive versions use O(V) call-stack space. A path of 100,000 vertices goes past Python's default recursion limit long before running time becomes a problem.
Exercise
A graph has V = 1,000 vertices and E = 50,000 edges. Roughly how many edge checks does Kosaraju's algorithm make in total, and how many does Tarjan's algorithm make?
Show answer
Kosaraju's algorithm checks each edge once in the first DFS, once when it builds the transpose, and once in the second DFS. That is about 150,000 edge operations. Tarjan's algorithm checks each edge once, for 50,000 edge checks. Both are O(V + E), but Kosaraju's algorithm has a larger constant factor.
Exercise
Why is the total number of stack pops in Tarjan's algorithm exactly V, even though some single while loops pop many vertices at once?
Show answer
Every vertex is pushed exactly once, when it is discovered, and a vertex can be popped only after it was pushed. Each vertex ends up in exactly one emitted component. Summed over all while loops, the pops therefore total V. This is an amortized bound: a single loop can be long, but the total work across all loops is still O(V).