Skip to contentKEEP THE CRAFTTHE SANCTUARY

Dijkstra

For nonnegative edge weights, expand the cheapest current tentative distance and relax its outgoing edges. Store best costs separately from heap entries so later improvements make older entries stale.

1 practice exercise3 interview problems

Recognize it when Weighted paths have nonnegative costs and BFS edge count is insufficient.

Checking your account…

Dijkstra Code Labs

Finalize the Cheapest Frontier State

Dijkstra uses a min-heap of candidate distances. With nonnegative edges, the cheapest non-stale popped distance cannot later be improved and is safe to expand.

Skip Stale Heap Entries

Python heaps do not decrease keys in place. Push improved candidates and skip a pop when its cost differs from the current distance table; otherwise obsolete paths repeat work.

Trace Dijkstra Heap Pops

Reference
import heapq

def dijkstra_pop_trace(adjacency,start):
    distance=[float("inf")]*len(adjacency);distance[start]=0;heap=[(0,start)];trace=[]
    while heap:
        cost,node=heapq.heappop(heap);stale=cost!=distance[node];trace.append([cost,node,stale])
        if stale:continue
        for neighbor,weight in adjacency[node]:
            candidate=cost+weight
            if candidate<distance[neighbor]:distance[neighbor]=candidate;heapq.heappush(heap,(candidate,neighbor))
    return trace
Practice

Implement dijkstra_pop_trace(adjacency,start). Return [distance,node,stale] for each heap pop; edges are [neighbor,nonnegative_weight].

Public tests

  • Identify stale candidate entries

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Dijkstra Heap Pops

import heapq

def dijkstra_pop_trace(adjacency,start):
    distance=[float("inf")]*len(adjacency);distance[start]=0;heap=[(0,start)];trace=[]
    while heap:
        cost,node=heapq.heappop(heap);stale=cost!=distance[node];trace.append([cost,node,stale])
        if stale:continue
        for neighbor,weight in adjacency[node]:
            candidate=cost+weight
            if candidate<distance[neighbor]:distance[neighbor]=candidate;heapq.heappush(heap,(candidate,neighbor))
    return trace

See a Direct Path Become a Stale Heap Entry

Run the existing heap-pop trace with direct edge cost 8 and indirect cost 5. Predict four rows rather than three: lazy updates retain the obsolete tuple until it is popped.

Step Executed statement State Why
Expand source cost,node=heapq.heappop(heap);candidate=cost+weight;distance[neighbor]=candidate;heapq.heappush(heap,(candidate,neighbor)) after source iteration: distance=[0,8,2] Both direct paths are tentative heap entries.
Expand node 2 cost,node=heapq.heappop(heap);candidate=cost+weight candidate=2+3=5 The indirect route beats the direct cost 8.
Update and push distance[neighbor]=candidate;heapq.heappush(heap,(candidate,neighbor)) distance[1]=5; heap holds costs 5 and 8 for node 1 Updating the table does not remove the old heap tuple.
Accept current pop cost,node=heapq.heappop(heap);stale=cost!=distance[node];trace.append([cost,node,stale]) cost=5, node=1, stale=False Nonnegative weights make this current minimum final.
Skip old pop cost,node=heapq.heappop(heap);stale=cost!=distance[node];trace.append([cost,node,stale]);continue cost=8, node=1, stale=True The trace records it, but outgoing edges are not expanded again. The continue executes in the actual stale branch.
Print Output
print(dijkstra_pop_trace([[[1, 8], [2, 2]], [], [[1, 3]]], 0)) [[0, 0, False], [2, 2, False], [5, 1, False], [8, 1, True]]

The None-based distance Lab preserves unreachable nodes separately from cost zero. Negative cycles are outside Dijkstra’s input contract, not a failure mode this routine promises to detect.

Relax Nonnegative Edges

For every outgoing edge, compare current cost plus weight with the neighbor’s best known distance. Nonnegative weight is the premise that makes heap-order finalization correct.

Compute Nonnegative Weighted Distances

Reference
import heapq

def dijkstra_distances(adjacency,start):
    distance=[None]*len(adjacency);distance[start]=0;heap=[(0,start)]
    while heap:
        cost,node=heapq.heappop(heap)
        if cost!=distance[node]:continue
        for neighbor,weight in adjacency[node]:
            candidate=cost+weight
            if distance[neighbor] is None or candidate<distance[neighbor]:distance[neighbor]=candidate;heapq.heappush(heap,(candidate,neighbor))
    return distance
Practice

Implement dijkstra_distances(adjacency,start). Return shortest costs, using None for unreachable nodes. Edges are [neighbor,nonnegative_weight] and start is a valid vertex index.

Public tests

  • Finalize cheapest available paths

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Nonnegative Weighted Distances

import heapq

def dijkstra_distances(adjacency,start):
    distance=[None]*len(adjacency);distance[start]=0;heap=[(0,start)]
    while heap:
        cost,node=heapq.heappop(heap)
        if cost!=distance[node]:continue
        for neighbor,weight in adjacency[node]:
            candidate=cost+weight
            if distance[neighbor] is None or candidate<distance[neighbor]:distance[neighbor]=candidate;heapq.heappush(heap,(candidate,neighbor))
    return distance

Choose Dijkstra or Bellman Ford

Use lazy-heap Dijkstra for nonnegative weights at O(V + E log(E + 1)); for a simple graph this simplifies to O((V + E) log V). Use Bellman-Ford when negative edges may occur and negative-cycle detection matters. Unit weights call for simpler BFS.

Explain It in an Interview

Say: “The heap’s cheapest current entry is final because every undiscovered continuation adds a nonnegative cost. Improved distances create new heap entries; stale ones are skipped.” Cover unreachable nodes and predecessor tracking.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Dijkstra's shortest path

Pop the cheapest, skip stale, relax neighbors.

Edges have non-negative weights and you need the cheapest path from a source.

Trigger words

  • weighted graph
  • network delay
  • cheapest path
  • minimum effort
  • non-negative weights
  • connect all points + cost
import heapq

def shortest_distances(graph, start):     # graph[node] = [(neighbor, weight), ...]
    dist = {start: 0}
    heap = [(0, start)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist[node]:
            continue                       # an older, longer entry
        for neighbor, weight in graph[node]:
            new_d = d + weight
            if neighbor not in dist or new_d < dist[neighbor]:
                dist[neighbor] = new_d
                heapq.heappush(heap, (new_d, neighbor))
    return dist

Spot it when

  • 'Network delay time', 'cheapest path', 'minimum effort'.
  • Weighted graph with no negative edges.

Remember

  • The heap always gives the unfinished node with the smallest known distance.
  • Skipping stale entries keeps the loop correct without a decrease-key operation.

How problems bend it

  • Grid with costs (swim in rising water): Nodes are cells; the cost of a path is its largest height, so push max(d, height).
  • At most k stops: Use Bellman-Ford style rounds instead: relax all edges k + 1 times from a copy of the distances.
  • Minimum spanning tree (Prim): Same heap loop, but push the single edge's cost instead of the path total, and add each node to the tree the first time it is popped.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Lazy-heap DijkstraO(V + E log(E + 1))O(V + E log(E + 1))Up to O(E) successful pushes; simplifies to O((V+E) log V) for a simple graph.

Space

O(V + E) distance and lazy heap storage beyond input; trace adds O(E) pop rows.

Assumptions

  • Python heapq uses lazy duplicate candidates here, not an indexed decrease-key heap.
  • Zero-weight edges are valid; strictly improving updates prevent equal-cost cycling.

Invariants Worth Saying Aloud

  1. A finite table value is the cheapest discovered path to that node.
  2. The minimum nonstale popped cost is final under nonnegative weights.
  3. A heap entry with a different cost from the table represents an obsolete path.

When To Use Or Avoid Dijkstra

Use It When

  • Use a min heap and nonnegative weights for sparse weighted graphs.
  • Use BFS instead when all weights are one, or 0-1 BFS for binary costs.

Choose Another Tool When

  • Negative edges invalidate the greedy finalization proof; use Bellman-Ford or DAG relaxation.
  • Marking a node final when first enqueued prevents later cheaper routes from improving it.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Finalizing on the first enqueue

A direct cost 9 may be improved to 3 through another node. Blocking updates after first discovery keeps 9.

Prevent it: Permit better tentative costs until a cheapest current pop finalizes the node.

Avoid

if neighbor not in discovered: distance[neighbor] = candidate

Use instead

if candidate < distance[neighbor]: distance[neighbor] = candidate

Expanding an obsolete heap candidate

A popped cost 9 disagrees with the current best cost 3. Using it expands an already replaced path.

Prevent it: Check the popped cost against the best table before exploring edges.

Avoid

expand = True

Use instead

expand = cost == distance[node]

Reading node ID before priority in heap tuples

(node,cost) chooses smaller labels rather than smaller path costs; node 1 at cost 9 overtakes node 2 at cost 3.

Prevent it: Put cost first and a deterministic comparable tie breaker second.

Avoid

heap = [(node, cost) for cost, node in entries]
heapq.heapify(heap)
node, cost = heapq.heappop(heap)

Use instead

heap = entries.copy()
heapq.heapify(heap)
cost, node = heapq.heappop(heap)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.