← Back to Algorithms, page 4

algorithms-0069 · Medium mid

Dijkstra's algorithm: compute shortest distances from a source in a graph with non-negative edge weights, and state the complexity the heap implementation actually has.

Keep a distance array and a min-heap of (distance, node). Pop the smallest entry, skip it if stale, and relax every outgoing edge, pushing improved distances. With a binary heap and lazy deletion, each edge pushes at most one entry, so the cost is O((V + E) log V) time and O(V + E) space. The heap-free array version is O(V^2 + E). Negative weights break the algorithm.

Full answer

Problem

Given a directed graph with n nodes, weighted edges (u, v, w) with w >= 0, and a source, return the shortest distance to every node (infinity if unreachable).

Example: edges (0,1,4), (0,2,1), (2,1,2), (1,3,1), (2,3,5) from 0 give distances [0, 3, 1, 4]: the best route to 1 is 0 to 2 to 1 with cost 3.

Constraints: up to 10^5 nodes and 2 * 10^5 edges; weights from 0 to 10^4.

Brute force

Bellman-Ford: relax all E edges V - 1 times, O(V * E). Correct for non-negative weights too, but far slower on large sparse graphs. Plain BFS is wrong because it ignores weights.

Optimal approach

  1. dist[src] = 0, all others infinity; heap [(0, src)].
  2. Pop (d, u). If d > dist[u], the entry is stale; skip it.
  3. For each edge (u, v, w): if d + w < dist[v], set dist[v] = d + w and push (dist[v], v).

Python's heapq has no decrease-key, so improved distances are pushed again and old entries are skipped (lazy deletion).

Why it works

When a node is popped with a non-stale distance, no shorter path to it can exist: any other path must leave the set of finalised nodes through some frontier node whose tentative distance is already at least d, and non-negative weights can only add to that. So each node's distance is final the first time it is popped. A negative edge breaks this argument, because a path through a later node could become cheaper.

Complexity

Correction to the earlier version of this item: the code below uses a binary heap with lazy deletion, so the complexity is O((V + E) log V) time, not O(V^2) and not O(E) alone.

  • Each edge relaxation can push one entry, so the heap holds O(E) entries and every push or pop costs O(log E). Since E <= V^2, log E <= 2 log V, which gives O((V + E) log V).
  • Space: O(V + E) for the adjacency list, the distances and the heap entries.
  • The array version (scan for the minimum unvisited node, no heap) is O(V^2 + E), which is better only for dense graphs where E is close to V^2. Fibonacci heaps give O(E + V log V) in theory but are rarely used in practice.

Code

python
import heapq
import random


def dijkstra(n, edges, src):
    """Binary-heap Dijkstra with lazy deletion. Non-negative weights only.
    Each edge can push one heap entry, so the heap holds O(E) items:
    O((V + E) log V) time (log E <= 2 log V), O(V + E) space."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                     # stale entry: u was already finalised with a smaller d
        for v, w in adj[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist


def dijkstra_array(n, edges, src):
    """Array version without a heap: pick the closest unvisited node by scanning. O(V^2 + E).
    Better than the heap only for dense graphs where E is close to V^2."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist, done = [INF] * n, [False] * n
    dist[src] = 0
    for _ in range(n):
        u = min((i for i in range(n) if not done[i]), key=lambda i: dist[i])
        if dist[u] == INF:
            break
        done[u] = True
        for v, w in adj[u]:
            dist[v] = min(dist[v], dist[u] + w)
    return dist


def bellman_ford_ref(n, edges, src):
    INF = float("inf")
    d = [INF] * n
    d[src] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
    return d


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
    assert dijkstra(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra_array(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra(3, [(0, 1, 0)], 0) == [0, 0, float("inf")]   # zero weight, unreachable node
    rng = random.Random(69)
    for _ in range(500):
        n = rng.randint(1, 9)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 9)) for _ in range(rng.randint(0, 25))]
        s = rng.randrange(n)
        assert dijkstra(n, es, s) == dijkstra_array(n, es, s) == bellman_ford_ref(n, es, s)
    print("all tests passed")

Save as b69_dijkstra.py and run python3 b69_dijkstra.py. It prints all tests passed (Python 3.13.5).

Edge cases

Unreachable nodes stay infinity. Zero-weight edges are allowed. Self-loops and parallel edges are harmless. Negative weights: use Bellman-Ford. Early exit: if only one target matters, stop when it is popped.

Pattern

Greedy shortest paths with a priority queue. Variants: path reconstruction with parent pointers, shortest path with a limited number of stops (state expansion), minimum effort or maximum probability paths (change the combine and compare operations), and A* (add an admissible heuristic to the priority).

python
import heapq
import random


def dijkstra(n, edges, src):
    """Binary-heap Dijkstra with lazy deletion. Non-negative weights only.
    Each edge can push one heap entry, so the heap holds O(E) items:
    O((V + E) log V) time (log E <= 2 log V), O(V + E) space."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                     # stale entry: u was already finalised with a smaller d
        for v, w in adj[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist


def dijkstra_array(n, edges, src):
    """Array version without a heap: pick the closest unvisited node by scanning. O(V^2 + E).
    Better than the heap only for dense graphs where E is close to V^2."""
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
    INF = float("inf")
    dist, done = [INF] * n, [False] * n
    dist[src] = 0
    for _ in range(n):
        u = min((i for i in range(n) if not done[i]), key=lambda i: dist[i])
        if dist[u] == INF:
            break
        done[u] = True
        for v, w in adj[u]:
            dist[v] = min(dist[v], dist[u] + w)
    return dist


def bellman_ford_ref(n, edges, src):
    INF = float("inf")
    d = [INF] * n
    d[src] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
    return d


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5)]
    assert dijkstra(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra_array(4, edges, 0) == [0, 3, 1, 4]
    assert dijkstra(3, [(0, 1, 0)], 0) == [0, 0, float("inf")]   # zero weight, unreachable node
    rng = random.Random(69)
    for _ in range(500):
        n = rng.randint(1, 9)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 9)) for _ in range(rng.randint(0, 25))]
        s = rng.randrange(n)
        assert dijkstra(n, es, s) == dijkstra_array(n, es, s) == bellman_ford_ref(n, es, s)
    print("all tests passed")

Heap version with lazy deletion and the O(V^2 + E) array version, both cross-checked against Bellman-Ford on random graphs including zero weights.

Complexity

Time: O((V + E) log V) heap version; O(V^2 + E) array version. Space: O(V + E). Fix applied: the claim now matches the code. Lazy deletion allows O(E) heap entries, and log E <= 2 log V.

By level

Fresher: Implements the heap version and traces it on the sample graph. Explains that the algorithm needs non-negative weights.

Mid: States O((V + E) log V) for the heap version and O(V^2 + E) for the array version, and picks between them by density. Explains lazy deletion and the correctness argument.

Senior: Discusses A*, bidirectional Dijkstra and contraction hierarchies used in road routing, and the cost of decrease-key heaps. Handles very large graphs with partitioning and precomputed landmarks.

Key points

  • Only for non-negative weights
  • Skip stale heap entries (d > dist[u])
  • A node's distance is final when first popped
  • Heap version O((V + E) log V); array version O(V^2 + E)
  • Use Bellman-Ford for negative weights

Common mistakes

  • Claiming O(V^2) for the heap code or O(V log V) without the edges
  • Not skipping stale entries, which reprocesses nodes
  • Using Dijkstra with negative edges
  • Marking nodes visited when pushed instead of when popped

Follow-ups

  • How do you reconstruct the shortest path?
  • How would you limit the route to at most k edges?
  • When is A* better, and what makes a heuristic admissible?

Tips

  • State the weight condition first
  • Explain lazy deletion in Python
  • Give the complexity for both implementations and when each wins

Evaluation rubric

  • Correct algorithm with stale-entry check
  • Complexity matches the code
  • Explains why negatives fail
  • Knows alternatives