Sub topic 12
Linear Time: O(V + E) Analysis
Both Kosaraju's and Tarjan's algorithms run in O(V + E) time, where V is the number of vertices and E is the number of edges. This chapter shows where that bound comes from, why no correct algorithm can do better, and which implementation mistakes push the real running time up to O(V²) or worse.
This chapter assumes you have read the earlier chapters on Kosaraju's and Tarjan's algorithms, know Big-O notation, and store graphs as adjacency lists (adj[u] is the list of vertices that u points to).
The Counting Argument Behind Every DFS
A loop nested inside a loop does not always mean quadratic time. A DFS has an outer loop over vertices and an inner loop over each vertex's edges. The total cost comes from adding up the work over the whole run, which is called aggregate analysis. It does not come from multiplying the worst case of each loop.
Two facts drive the analysis:
- Each vertex is entered exactly once. The
visitedcheck (orindex[v] is Nonein Tarjan's algorithm) guarantees that a vertex cannot be entered a second time. - When a vertex
uis entered, the loop scansadj[u]once. Adding over all vertices, the inner loops dolen(adj[0]) + len(adj[1]) + ... + len(adj[V-1]) = Eiterations in total.
Each edge iteration does O(1) work: an array lookup, a comparison, and possibly a recursive call. The cost of that recursive call is already counted under fact 1. One full DFS therefore costs O(V) for entering vertices plus O(E) for scanning edges, which gives O(V + E).
Kosaraju's Algorithm, Phase by Phase
Kosaraju's algorithm runs in separate phases. Each phase is linear on its own, so their sum is linear too.
| Phase | Work done | Cost |
|---|---|---|
| First DFS | Each vertex entered once, each edge of G scanned once, each vertex appended to `order` once | O(V + E) |
| Transpose | Allocate V empty lists, then one `append` per edge | O(V + E) |
| Second DFS | Each vertex labeled once, each edge of the transpose scanned once | O(V + E) |
| Reverse iteration | `reversed(order)` walks V entries | O(V) |
Reading the finish order backwards is cheap. The code never sorts by finish time. It appends each vertex at the moment it finishes, so order is already sorted by finish time when the first DFS ends. Using a comparison sort would cost O(V log V) and would be unnecessary.
Tarjan's Algorithm and the Popping Loop
Tarjan's algorithm does a single DFS, so the vertex and edge counting from above applies directly. Each edge does one min update on low[v], which costs O(1). The part that needs care is the inner while True loop that pops a component off the stack.
A single call to strongconnect can pop many vertices. If the whole graph is one big cycle, the root's call pops all V vertices. That looks expensive until you count across the entire run:
- Each vertex is pushed onto
stackexactly once, when it is discovered. - A vertex is popped at most once for each time it is pushed.
- So all the popping loops together run at most V iterations.
This is the same amortized argument used for a stack with a "pop many" operation. Some calls do a lot of popping and most do none, and the total stays bounded by V. Adding everything up: O(V) for discoveries, O(E) for edge scans and low-link updates, and O(V) for all pushes and pops, for a total of O(V + E).
Checking the Counts Empirically
The following script adds counters to Kosaraju's algorithm and runs it on random graphs. It checks that the number of vertex visits is exactly 2V and the number of edge checks is exactly 2E, one of each per pass.
import random
import sys
sys.setrecursionlimit(10000)
def kosaraju_counted(n, adj):
ops = {"vertex_visits": 0, "edge_checks": 0}
visited = [False] * n
order = []
def dfs1(u):
ops["vertex_visits"] += 1
visited[u] = True
for v in adj[u]:
ops["edge_checks"] += 1
if not visited[v]:
dfs1(v)
order.append(u)
for u in range(n):
if not visited[u]:
dfs1(u)
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
def dfs2(u, c):
ops["vertex_visits"] += 1
comp[u] = c
for v in radj[u]:
ops["edge_checks"] += 1
if comp[v] == -1:
dfs2(v, c)
c = 0
for u in reversed(order):
if comp[u] == -1:
dfs2(u, c)
c += 1
return comp, ops
random.seed(1)
for n, m in [(50, 100), (200, 800), (400, 3000)]:
adj = [[] for _ in range(n)]
for _ in range(m):
adj[random.randrange(n)].append(random.randrange(n))
comp, ops = kosaraju_counted(n, adj)
print(n, m, ops,
ops["vertex_visits"] == 2 * n,
ops["edge_checks"] == 2 * m)Every line ends with True True. The counts are exact because every edge is scanned once per pass, whether or not it leads to a new vertex. Self-loops and parallel edges are scanned too, and they still count toward E.
Why You Cannot Beat O(V + E)
Any correct SCC algorithm has to read every edge. Suppose an algorithm skipped the edge u → v and reported u and v in different components, with a path from v back to u elsewhere in the graph. The algorithm would give the same answer whether or not that edge existed. With the edge, u and v belong to the same SCC. Without it, they do not. So the algorithm is wrong on one of the two graphs. It also has to assign a label to every vertex, which costs Ω(V). The bound is therefore Θ(V + E), and both algorithms are optimal up to constant factors.
Space Complexity
| Structure | Kosaraju | Tarjan |
|---|---|---|
| Input adjacency lists | O(V + E) | O(V + E) |
| Per-vertex arrays | `visited`, `comp`, `order`: O(V) | `index`, `low`, `on_stack`: O(V) |
| Transpose | O(V + E) extra | none |
| Explicit SCC stack | none | O(V) |
| Recursion depth | up to V frames | up to V frames |
Both algorithms need O(V + E) space in total because they hold the input. The extra space beyond the input is O(V + E) for Kosaraju (because of the transpose) and O(V) for Tarjan. On a graph with 10⁸ edges, that difference decides whether the program fits in memory. The recursion depth can reach V on a long path, which is why a later chapter covers iterative versions.
Hidden Quadratic Traps
The O(V + E) bound only holds if every "O(1)" step really takes constant time. The following mistakes are common, and each one breaks that assumption.
| Mistake | Why it is slow | Fix |
|---|---|---|
| `if w in stack:` instead of `on_stack[w]` | A list membership test scans the list: O(V) per edge, O(VE) total | Keep a boolean array |
| `order.insert(0, u)` to build decreasing finish order | Each insert shifts the whole list: O(V²) | `append`, then iterate `reversed(order)` |
| Adjacency matrix instead of lists | Scanning neighbors costs O(V) per vertex: O(V²) | Use adjacency lists |
| Rebuilding `radj[v] = radj[v] + [u]` | Copies the list on every edge | Use `radj[v].append(u)` |
| Computing the transpose inside the second DFS | The transpose gets rebuilt for every component | Build it once, before the second pass |
| Sorting vertices by finish time | O(V log V), which is still correct but unnecessary | Record vertices at finish time |
Building the condensation DAG also stays linear when duplicate edges between components go through a set (expected O(1) per insertion) or are removed with a final sort-and-deduplicate pass. Checking if x not in dag_list would bring the quadratic behavior back.
Exercises
Exercise
In Tarjan's algorithm, one call to strongconnect can pop V vertices from the stack. Why doesn't this make the algorithm O(V²)?
Show answer
Each vertex is pushed onto the stack exactly once, when it is discovered, and can be popped at most once. All the popping loops together therefore run at most V iterations over the whole execution. A single expensive call uses up pushes that no other call can pop again, so the total popping cost is O(V).
Exercise
A programmer runs Kosaraju's algorithm on a graph stored as a V × V adjacency matrix, scanning row u to find the neighbors of u. What is the running time, and for which graphs does it match O(V + E)?
Show answer
Each vertex scans a full row of V entries in each pass, so the running time is Θ(V²) no matter how many edges there are. This matches O(V + E) only for dense graphs, where E = Θ(V²). For sparse graphs, it is much slower than the adjacency-list version.
Exercise
In the instrumented script, edge_checks equals exactly 2E even on graphs with self-loops and duplicate edges. Explain why.
Show answer
The inner loop of each DFS goes over every entry of adj[u] (or radj[u]) exactly once, when u is entered, and each vertex is entered once per pass. A self-loop or duplicate edge is a separate list entry, so it is scanned once in the first pass and once in the second, whether or not it leads to an unvisited vertex.