Sub topic 10
Running Time and Memory Use
This chapter assumes you know Big-O notation, can read the heap-based dijkstra function from the implementation chapter, and know how a binary heap supports push and pop in logarithmic time. We use V for the number of vertices and E for the number of edges throughout.
The cost of Dijkstra's algorithm depends on the priority queue you use. The relaxation logic stays the same in every version. What changes is how quickly you can find the closest unvisited vertex and how cheaply you can record a better distance. This chapter counts those operations for three priority-queue choices: a plain array, a binary heap with lazy deletion, and a Fibonacci heap. It also covers what each choice costs in memory.
Counting the Work
Every version of Dijkstra's algorithm does the same three kinds of work:
- Select: find and remove the unvisited vertex with the smallest tentative distance. This happens at most once per reachable vertex, so up to V times.
- Relax: look at each outgoing edge of the selected vertex. Each edge is examined once, when its tail vertex is finalized, so this happens E times in total.
- Update: when relaxation finds a shorter distance, tell the priority queue about it. This happens at most once per relaxation, so up to E times.
Total running time is roughly V × (cost of select) + E × (cost of update). The adjacency-list scan itself adds O(V + E). The priority queue sets the select and update costs, and you can trade one against the other.
The Array Implementation: O(V²)
The simplest priority queue is no data structure at all. Keep a dist table and scan every unvisited vertex to find the minimum. Selection costs O(V) and an update is a single assignment costing O(1).
import math
def dijkstra_array(graph, source):
"""O(V^2) Dijkstra: linear scan for the minimum, O(1) updates."""
nodes = set(graph)
for u in graph:
for v, _ in graph[u]:
nodes.add(v)
dist = {v: math.inf for v in nodes}
dist[source] = 0
visited = set()
for _ in range(len(nodes)):
u = min((v for v in nodes if v not in visited), key=lambda v: dist[v])
if dist[u] == math.inf:
break # remaining vertices are unreachable
visited.add(u)
for v, w in graph.get(u, []):
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
print(sorted(dijkstra_array(graph, "A").items()))
# [('A', 0), ('B', 3), ('C', 1), ('D', 4)]V scans of O(V) each give O(V²), and the E updates add O(E). Since a simple directed graph has E ≤ V(V − 1), the total is O(V²) whatever the edge count.
Being independent of edge density is useful. On a dense graph, where E is close to V², this is optimal: you have to read every edge anyway, and that alone costs Θ(V²).
The Binary Heap with Lazy Deletion: O(E log V)
The heap version from the implementation chapter never changes an entry already in the heap. Each improvement pushes a new (distance, vertex) tuple, and outdated tuples are skipped when popped. This is called lazy deletion.
Here is how to count the cost:
- Every push comes from a successful relaxation, plus the single initial push of the source. So there are at most E + 1 pushes.
- Every entry is popped at most once, so there are at most E + 1 pops, stale entries included.
- The heap never holds more than E + 1 entries, so each push or pop costs O(log E).
That gives O(E log E). Because E ≤ V², log E ≤ 2 log V, so O(log E) = O(log V) and the bound is usually written O(E log V). Adding the O(V + E) adjacency scan gives O((V + E) log V). When every vertex is reachable, E ≥ V − 1, so the E term dominates.
Measuring the Stale Entries
The bound of E + 1 pushes is tight. The instrumented version below counts pushes, stale pops, and the peak heap size on a graph built so that the target improves at every step.
import heapq
def dijkstra_counted(graph, source):
dist = {source: 0}
heap = [(0, source)]
visited = set()
pushes, stale, max_heap = 1, 0, 1
while heap:
d, u = heapq.heappop(heap)
if u in visited:
stale += 1
continue
visited.add(u)
for v, w in graph.get(u, []):
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
pushes += 1
max_heap = max(max_heap, len(heap))
return dist, pushes, stale, max_heap
# S reaches v1..v5 with weights 1..5; each vi reaches T more cheaply than the last.
graph = {"S": [(f"v{i}", i) for i in range(1, 6)], "T": []}
for i in range(1, 6):
graph[f"v{i}"] = [("T", 10 - 2 * i)]
dist, pushes, stale, max_heap = dijkstra_counted(graph, "S")
edges = sum(len(adj) for adj in graph.values())
print("T distance:", dist["T"]) # T distance: 5
print("edges:", edges, "pushes:", pushes) # edges: 10 pushes: 11
print("stale pops:", stale) # stale pops: 4
print("peak heap size:", max_heap) # peak heap size: 5T's tentative distance falls from 9 to 5 in five steps, which leaves four stale copies in the heap. Here the push count reaches the bound of E + 1 = 11 exactly. On typical road or network graphs, far fewer relaxations succeed, and stale entries are a small fraction of the total.
The Fibonacci Heap: O(E + V log V)
A Fibonacci heap supports decrease-key in O(1) amortized time and extract-min in O(log V) amortized time. With V extractions and up to E decrease-keys, the total is O(E + V log V). This is the best known bound for Dijkstra's algorithm with comparison-based priority queues on general graphs. A later chapter covers how decrease-key works and why Fibonacci heaps are rarely used in practice.
Comparing the Three
| Priority queue | Select-min | Update | Total time | Extra memory |
|---|---|---|---|---|
| Unsorted array | O(V) | O(1) | O(V²) | O(V) |
| Binary heap, lazy deletion | O(log V) | O(log V) push | O(E log V) | O(E) heap entries |
| Binary heap, decrease-key | O(log V) | O(log V) | O((V + E) log V) | O(V) plus position index |
| Fibonacci heap | O(log V) amortized | O(1) amortized | O(E + V log V) | O(V), large per-node overhead |
The chart below plugs V = 1,000 into each formula, using log₂ V ≈ 10 and ignoring constant factors, and varies the edge count.
The binary heap and the array cost about the same when E log V ≈ V², which means E ≈ V² / log V. Below that density the heap wins, and above it the array wins.
Memory Use
Every version stores dist, prev, and visited, which take O(V) space. The graph itself takes O(V + E) as an adjacency list. The priority queue is where the versions differ:
- Array: no extra structure beyond
dist. - Lazy-deletion heap: up to E + 1 tuples. In CPython, each tuple with its contents takes several dozen bytes, so on a graph with ten million edges the heap alone can approach a gigabyte in the worst case.
- Decrease-key heap: at most V entries, plus a map from vertex to heap position, which you must update on every swap.
- Fibonacci heap: O(V) nodes, but each one carries parent, child, sibling, degree, and mark fields.
Choosing an Implementation
- Sparse graphs, where E is O(V) or close to it: road networks, grids, most real-world networks. Use the binary heap. It costs O(V log V), and
heapqis fast because it is written in C. - Dense graphs, where E is close to V², or graphs stored as an adjacency matrix: use the array version. It is O(V²) with no heap overhead, and its inner loop vectorizes well in NumPy.
- Very large sparse graphs where memory is tight: consider a decrease-key heap, which caps the queue at V entries.
- Fibonacci heaps: these matter for theoretical bounds. Their large constant factors and poor cache behavior usually make them slower than a binary heap at practical sizes.
Common Errors in Complexity Reasoning
- Assuming the heap holds at most V entries. With lazy deletion it can hold up to E + 1. The time bound still holds, but your memory estimate will be wrong.
- Calling the heap version O(V log V). That leaves out the E relaxations, each of which can trigger a push.
- Assuming the heap version always wins. On dense graphs, O(E log V) becomes O(V² log V), which is worse than the array.
- Forgetting unreachable vertices. The heap version never touches them. The array version above stops scanning once the minimum distance is infinite, but a naive array version that never checks for this wastes its remaining scans on them.
Exercise
A graph has V = 10,000 vertices and E = 30,000 edges. Estimate the operation counts for the array and binary-heap implementations, using log2 V ≈ 13, and say which implementation you would choose.
Show answer
The array version takes about V² = 100,000,000 operations. The binary heap takes about E log V ≈ 30,000 × 13 = 390,000 operations. The graph is sparse, so the binary heap is roughly 250 times cheaper by this estimate, and it is the right choice.
Exercise
Explain why a lazy-deletion heap never holds more than E + 1 entries, and why its O(E log E) bound is the same as O(E log V).
Show answer
An entry is pushed only for the initial source and for each successful relaxation. Each edge is relaxed once, when its tail is finalized, so there are at most E + 1 pushes, and the heap can never hold more entries than have been pushed. In a simple graph E ≤ V², so log E ≤ 2 log V. Constant factors disappear in Big-O, so O(E log E) = O(E log V).
Exercise
You must run Dijkstra's algorithm on a complete graph with 2,000 vertices, stored as a 2,000 × 2,000 distance matrix. Which implementation do you pick, and what is its running time?
Show answer
Pick the array implementation. E is about V² = 4,000,000, so the binary heap costs O(V² log V), roughly 44 million operations, plus up to 4 million heap entries in memory. The array version costs O(V²), about 4 million operations, needs only O(V) extra memory, and reads the matrix rows directly.