Sub topic 10
Running Time and Memory Use
This chapter assumes you know Big-O notation and have read the earlier chapter that builds Dijkstra's algorithm with heapq and lazy deletion. Throughout, V is the number of vertices and E is the number of edges.
Where the Work Happens
Every version of Dijkstra's algorithm does two kinds of work:
- Selecting the closest unvisited vertex. This happens once per vertex, so V times.
- Relaxing an outgoing edge, which means checking whether it gives a shorter distance to its neighbor. Each edge is relaxed once, when its tail vertex is finalized, so E times.
The total cost is V selections plus E relaxations, and the priority queue sets the price of each. That makes the choice of data structure the main factor in running time.
Three Implementations Compared
| Priority queue | Select min | Relax (update) | Total time |
|---|---|---|---|
| Unsorted array | O(V) scan | O(1) overwrite | O(V²) |
| Binary heap, lazy deletion | O(log E) pop | O(log E) push | O((V + E) log V) |
| Fibonacci heap | O(log V) amortized | O(1) amortized decrease-key | O(E + V log V) |
The binary heap row uses log E, and that still counts as O(log V). A simple graph has E ≤ V², so log E ≤ 2 log V.
Which one wins
- Sparse graphs (E close to V, as in road networks): the binary heap gives O(V log V), much better than O(V²).
- Dense graphs (E close to V²): the heap costs O(V² log V), and the plain array's O(V²) is actually faster. An array scan also has good cache behavior and no heap overhead.
- Fibonacci heaps have the best bound on paper. In practice their large constant factors and pointer-heavy layout usually make them slower than a binary heap. A later chapter covers this in more detail.
Memory Use
| Structure | Space |
|---|---|
| Adjacency list | O(V + E) |
| `dist`, `prev`, `visited` | O(V) |
| Heap with lazy deletion | O(E) in the worst case |
Lazy deletion never removes an outdated entry. It pushes a new one each time a distance improves, so the heap can hold up to one entry per edge, plus the source. Total extra space is O(V + E), which is no worse than storing the graph itself.
Measuring Heap Growth
The code below counts pushes and stale pops on a complete graph. The weights are chosen so that distances keep improving, which makes the heap grow.
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 pushes, stale, max_heap
n = 200
# Edge i->j costs (j - i) * n - i for j > i: later hops keep improving distances.
graph = {i: [(j, (j - i) * n - i) for j in range(i + 1, n)] for i in range(n)}
edges = sum(len(adj) for adj in graph.values())
pushes, stale, max_heap = dijkstra_counted(graph, 0)
print("V =", n, "E =", edges)
print("pushes =", pushes, "stale pops =", stale, "max heap size =", max_heap)On this graph, vertex 1 lowers the distance to every later vertex, then vertex 2 lowers them again, and so on. The push count lands well above V and approaches E. Each of those extra entries is eventually popped and skipped as stale. That skipping is the hidden cost that the O(E log V) bound accounts for.
Exercise
A graph has V = 10,000 vertices and E = 30,000 edges. Roughly how many basic steps do the array version and the binary-heap version take, and which should you use?
Show answer
Array: V² = 100,000,000 steps. Binary heap: (V + E) log₂ V ≈ 40,000 × 13.3 ≈ 530,000 steps. The graph is sparse, so use the binary heap. It does about 190 times less work.
Exercise
Why can the lazy-deletion heap hold more than V entries, and what is its upper bound?
Show answer
Each successful relaxation pushes a new entry without removing the old one, so a vertex can appear several times. There is at most one push per edge plus the initial source push, so the heap holds at most E + 1 entries, which is O(E).