Sub topic 6
Why DFS Runs in O(V + E)
This chapter assumes you have read the chapters on recursive and iterative DFS. It also assumes you can read Big-O notation and know that Python set membership tests take expected constant time. Here you will see why DFS on an adjacency list costs O(V + E) time. V is the number of vertices and E is the number of edges. You will also see which implementation mistakes break that bound.
The accounting argument
The usual first try at analysing DFS goes like this: "each vertex may have up to V neighbors, so the cost is V × V." That bound is correct but loose. A better method is aggregate analysis. Instead of bounding the worst single step, you count the total work done over the whole run.
DFS does two kinds of work:
- Per-vertex work. It marks the vertex visited, appends it to the output, and sets up a loop. This is constant work, and the visited set guarantees it happens at most once per vertex. Total: O(V).
- Per-edge work. Inside a vertex's loop, DFS looks at each neighbor once and checks whether it has been visited. That check is constant time with a hash set. A vertex's adjacency list is scanned only when the vertex is visited, so each list is scanned at most once.
The total length of all adjacency lists is the sum of the out-degrees. In a directed graph that sum is exactly E. In an undirected graph each edge {u, v} is stored twice, once in u's list and once in v's, so the sum is 2E. Either way the edge work is O(E).
Adding the two parts gives O(V + E). The plus sign matters. A vertex with 1,000 neighbors costs 1,000 checks, and a vertex with 2 neighbors costs 2. You pay for the edges that actually exist, not for a worst case repeated at every vertex.
Checking the argument by counting
You can instrument DFS and watch the counts match the theory. The function below counts vertex visits and neighbor checks.
def dfs_counted(graph, start):
visited = set()
counts = {"vertex_visits": 0, "edge_checks": 0}
def visit(node):
visited.add(node)
counts["vertex_visits"] += 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"))
# {'vertex_visits': 4, 'edge_checks': 4}
triangle = {"A": ["B", "C"], "B": ["A", "C"], "C": ["A", "B"]}
print(dfs_counted(triangle, "A"))
# {'vertex_visits': 3, 'edge_checks': 6}The directed graph has V = 4 and E = 4, and the counts are exactly 4 and 4. The undirected triangle has 3 edges, and the code makes 6 checks, which is 2E. Notice that vertex D in the directed graph is reachable twice, through B and through C. It is still visited only once. The edge C → D costs one check that finds D already visited, and nothing more.
The cost depends on the representation
The O(V + E) bound depends on being able to list a vertex's neighbors in time proportional to how many there are. Other representations change that.
| Representation | Cost to list neighbors of one vertex | Total DFS time |
|---|---|---|
| Adjacency list (dict of lists) | O(deg(v)) | O(V + E) |
| Adjacency matrix | O(V), scanning a whole row | O(V²) |
| Plain edge list, scanned for each vertex | O(E) | O(V · E) |
On a dense graph, where E is close to V², the matrix costs about the same as the list. On a sparse graph, such as a road network or a dependency graph with a few edges per vertex, the matrix wastes most of its time reading zeros. That is why the earlier chapter on representation preferred adjacency lists.
Space complexity
DFS keeps three things in memory besides the graph itself.
| Structure | Worst-case size | When the worst case happens |
|---|---|---|
| Visited set | O(V) | Every vertex is reachable |
| Recursion stack (recursive DFS) | O(V) | The graph is a long path, so the depth reaches V |
| Explicit stack (push-all-neighbors iterative DFS) | O(E) | Many edges point to vertices that have not been popped yet |
The last row catches people out. The iterative version from the previous chapter marks a vertex visited when it is popped, not when it is pushed. A vertex can therefore sit on the stack several times, once for each edge that reached it before it was popped. The total number of pushes is at most E + 1: one for the start vertex, plus at most one per edge scan. So the time stays O(V + E), but the stack can grow past V.
def dfs_iterative_stats(graph, start):
visited = set()
stack = [start]
pushes = 0
max_stack = 1
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
pushes += 1
max_stack = max(max_stack, len(stack))
return pushes, max_stack
n = 5
complete = {u: [v for v in range(n) if v != u] for u in range(n)}
print(dfs_iterative_stats(complete, 0)) # (10, 7)The complete directed graph on 5 vertices has E = 20. DFS made 10 pushes, within the bound, and the stack peaked at 7 entries even though V is only 5. On a complete graph with n vertices this variant makes n(n − 1)/2 pushes, so its stack really does grow quadratically. If memory is tight, push an iterator over each vertex's neighbors instead of the neighbors themselves. That mirrors the call stack exactly and keeps the stack at O(V).
Common mistakes that break the bound
Using a list for visited
neighbor not in visited takes expected O(1) time when visited is a set. When visited is a list it takes O(V) time, because Python compares the neighbor with each element in turn. Each of the O(E) checks then costs O(V), and the total becomes O(V · E). On small test graphs the code looks correct and fast, and it slows down badly on real inputs.
Rebuilding neighbors on every visit
If graph[node] is computed on demand, the cost of building the list gets added to each visit. For example, a function that filters a global edge list to find the edges leaving node makes every neighbor lookup cost O(E). Build the adjacency list once, before the traversal starts.
Forgetting the outer loop's cost
A full-graph traversal, which launches DFS from every unvisited vertex, adds a loop over all V vertices. That loop costs O(V), so the total is still O(V + E). Vertices with no edges still count. A graph with a million isolated vertices and no edges costs O(V), not O(1).
Recursion depth is a practical limit
The recursive version's O(V) stack depth is fine in theory. In CPython the default recursion limit is about 1,000 frames, so a path of 5,000 vertices raises RecursionError. You can raise the limit with sys.setrecursionlimit, but very deep recursion can still crash the interpreter by overflowing the C stack. For deep graphs, use the iterative version.
Summary of the bounds
- Time: O(V + E) with an adjacency list and a hash-set visited structure.
- Time with an adjacency matrix: O(V²).
- Space: O(V) for visited and recursion. The push-all-neighbors iterative stack can reach O(E).
- The bound holds for directed graphs (sum of degrees = E) and undirected graphs (sum of degrees = 2E).
Exercise
An undirected graph has 6 vertices and 9 edges and is stored as an adjacency list. A full-graph DFS runs over it. Exactly how many neighbor checks does it make, and why does that number not depend on the start vertex?
Show answer
It makes 18 checks. Each undirected edge appears in two adjacency lists, so the lists have 2 × 9 = 18 entries in total. A full-graph traversal visits every vertex exactly once and scans each list exactly once, so it checks every entry once whatever the start vertex or traversal order.
Exercise
A colleague's DFS stores visited vertices in a Python list and runs on a sparse graph with V = 100,000 and E = 300,000. Estimate the order of magnitude of the membership-check work, and give the one-line fix.
Show answer
Each of the roughly 300,000 checks scans a list that grows to 100,000 entries, so the work is on the order of 10^10 comparisons, which is O(V · E). Changing visited = [] to visited = set() (and append to add) makes each check expected O(1), which brings the total back to O(V + E), on the order of 4 × 10^5 operations.
Exercise
Why can the push-all-neighbors iterative DFS hold more than V entries on its stack, and what bound does its total number of pushes always respect?
Show answer
A vertex is marked visited only when popped, so it can be pushed once for each edge that reaches it before it is popped, which creates duplicates. Every push except the first one comes from scanning an edge, and each edge is scanned at most once, so the total number of pushes is at most E + 1.