Sub topic 6
Why DFS Runs in O(V + E)
This chapter assumes you can read the recursive and iterative DFS from the previous chapters, you know Big-O notation, and you know that Python set membership checks take O(1) time on average. Here V is the number of vertices and E is the number of edges.
Where the Work Happens
DFS does two kinds of work:
- Per-vertex work. It marks a vertex visited, records it, and starts scanning that vertex's neighbors. The visited check makes sure this happens at most once per vertex. That totals O(V).
- Per-edge work. Inside the loop over
graph[node], DFS checks one neighbor at a time. Each adjacency list is scanned only once, when its vertex is visited, so the total number of checks is the sum of all list lengths.
For a directed graph, the adjacency lists together hold E entries. For an undirected graph, each edge appears in two lists, so they hold 2E entries. Either way, the edge work is O(E).
The two totals add together. They do not multiply, because DFS never rescans an adjacency list. So the running time is O(V + E).
Counting It Directly
You can confirm the bound by instrumenting DFS to count both kinds of work:
def dfs_counted(graph, start):
visited = set()
counts = {"vertices": 0, "edge_checks": 0}
def visit(node):
visited.add(node)
counts["vertices"] += 1
for neighbor in graph[node]:
counts["edge_checks"] += 1
if neighbor not in visited:
visit(neighbor)
visit(start)
return counts
directed = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs_counted(directed, "A")) # {'vertices': 4, 'edge_checks': 4}
triangle = {"A": ["B", "C"], "B": ["A", "C"], "C": ["A", "B"]}
print(dfs_counted(triangle, "A")) # {'vertices': 3, 'edge_checks': 6}The directed graph has 4 edges and DFS makes 4 checks. The undirected triangle has 3 edges and DFS makes 6 checks, which is 2E.
Space Complexity
- Visited set: O(V).
- Recursion depth: O(V) in the worst case. On a path graph
A → B → C → ..., every vertex sits on the call stack at once. Python's default recursion limit is about 1,000, so long paths raiseRecursionError. - Explicit stack: The iterative version from the previous chapter pushes a neighbor every time it is unvisited at check time, so the same vertex can be pushed more than once. The stack can therefore hold O(E) entries, though it still does O(V + E) total work.
How Representation Changes the Bound
The bound depends on getting each vertex's neighbors quickly.
| Representation | Cost to list neighbors of v | Total DFS time |
|---|---|---|
| Adjacency list | O(deg(v)) | O(V + E) |
| Adjacency matrix | O(V) | O(V²) |
| Plain edge list, scanned per vertex | O(E) | O(V · E) |
Common Errors
- Claiming O(V · E) because of the nested loop. The inner loop runs over one vertex's list at a time, and the outer recursion covers each vertex once. Add up the list lengths across the whole run instead of multiplying the worst cases.
- Forgetting the V term. A graph with many isolated vertices and almost no edges still costs O(V) to traverse fully.
- Assuming E is always small. In a dense graph E approaches V², so O(V + E) becomes O(V²).
Exercise
An undirected graph with 1,000 vertices and 5,000 edges is stored as adjacency lists and is connected. Exactly how many neighbor checks does dfs_counted perform, and how many vertex visits?
Show answer
It performs 10,000 neighbor checks, because each of the 5,000 edges appears in two adjacency lists and each list is scanned once. It makes 1,000 vertex visits, because the graph is connected and the visited set prevents repeats.
Exercise
A graph has V vertices and is stored as an adjacency matrix. Why does DFS take O(V²) even if the graph has only V − 1 edges?
Show answer
Finding the neighbors of each vertex means scanning its entire matrix row of V entries, whether or not they are edges. Doing this for V vertices costs O(V²) no matter how few edges exist.