Skip to contentKEEP THE CRAFTTHE SANCTUARY

Shortest Path

Select a shortest-path method from edge costs and graph structure. Distances are discovered-path upper bounds; relaxation, finalization and negative-cycle handling depend on the selected method.

1 practice exercise1 interview problem

Recognize it when A question asks for minimum total cost or fewest moves between states.

Checking your account…

Shortest Path Code Labs

Match Edge Costs to the Algorithm

Shortest path is a family of problems. Use BFS for unit edges, Dijkstra for nonnegative weights, Bellman-Ford for possible negative weights, and DAG relaxation when a topological order exists.

Maintain Distance Upper Bounds

A recorded distance is the cheapest path found so far, initially infinity except zero at the source. It becomes final only under the selected algorithm’s proof.

Trace Edge Relaxations

Reference
def relaxation_trace(node_count,edges,start):
    distance=[None]*node_count;distance[start]=0;trace=[]
    for source,target,weight in edges:
        if distance[source] is not None:
            candidate=distance[source]+weight
            if distance[target] is None or candidate<distance[target]:distance[target]=candidate;trace.append(distance.copy())
    return trace
Practice

Implement relaxation_trace(node_count,edges,start). Process weighted directed edges once in order and return distances after every successful relaxation; unreachable is None. node_count is positive, start and all edge endpoints are valid vertex indices.

Public tests

  • Improve only through reachable sources

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

Trace Edge Relaxations

def relaxation_trace(node_count,edges,start):
    distance=[None]*node_count;distance[start]=0;trace=[]
    for source,target,weight in edges:
        if distance[source] is not None:
            candidate=distance[source]+weight
            if distance[target] is None or candidate<distance[target]:distance[target]=candidate;trace.append(distance.copy())
    return trace

One Edge Pass Can Leave a Reachable Node Unresolved

Predict the existing relaxation Lab in the deliberately unfavorable edge order shown. Its final snapshot is not the true shortest-path answer; it exposes why a general algorithm needs a processing or repetition proof.

Step Executed statement State Why
Initialize distance=[None]*node_count;distance[start]=0;trace=[] distance=[0, None, None] Only the source has a known path.
Skip first edge if distance[source] is not None: edge 1->2 skipped Node 1 is not reachable in the current table yet.
Discover node 1 candidate=distance[source]+weight;distance[target]=candidate;trace.append(distance.copy()) distance=[0, 3, None] The later 0->1 edge creates a usable prefix.
Direct node 2 path candidate=distance[source]+weight;distance[target]=candidate;trace.append(distance.copy()) distance=[0, 3, 9] One pass does not revisit 1->2, so it misses the cheaper total 5.
Print Output
print(relaxation_trace(3, [[1, 2, 2], [0, 1, 3], [0, 2, 9]], 0)) [[0, 3, None], [0, 3, 9]]

BFS’s layer order, Dijkstra’s nonnegative-cost order, DAG order and repeated Bellman-Ford passes are different ways to provide that missing guarantee. Name the guarantee instead of treating relaxation alone as an algorithm.

Relax Only Through Reachable States

For edge u to v with weight w, propose distance[u] + w only when u is reachable. Replace distance[v] if the candidate is smaller and record predecessor when path reconstruction is required.

Find Unweighted Shortest Paths

Reference
from collections import deque

def unweighted_distances(adjacency,start):
    distance=[-1]*len(adjacency);distance[start]=0;queue=deque([start])
    while queue:
        node=queue.popleft()
        for neighbor in adjacency[node]:
            if distance[neighbor]==-1:distance[neighbor]=distance[node]+1;queue.append(neighbor)
    return distance
Practice

Implement unweighted_distances(adjacency,start). Return shortest edge counts or -1 for unreachable nodes. adjacency is nonempty; start and every neighbor are valid vertex indices.

Public tests

  • Use first BFS discovery

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

Find Unweighted Shortest Paths

from collections import deque

def unweighted_distances(adjacency,start):
    distance=[-1]*len(adjacency);distance[start]=0;queue=deque([start])
    while queue:
        node=queue.popleft()
        for neighbor in adjacency[node]:
            if distance[neighbor]==-1:distance[neighbor]=distance[node]+1;queue.append(neighbor)
    return distance

Detect Unreachable and Negative Cases

Use an explicit unreachable sentinel and never add weights to it. Negative edges invalidate Dijkstra’s finalization proof; reachable negative cycles mean no finite shortest distance for affected vertices.

Choose BFS instead of a weighted algorithm for unit edges. Choose Dijkstra for nonnegative weights, Bellman-Ford for possible negative weights, and topological relaxation for a weighted DAG.

Explain It in an Interview

Say: “These edge costs justify this algorithm. Distances are upper bounds, and relaxation improves one through a known reachable prefix.” State directedness, unreachable output, path reconstruction, and the precise complexity for the selected method.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Unweighted BFSO(V + E)O(V + E)Unit-cost edges.
DAG relaxationO(V + E)O(V + E)Includes obtaining a topological order.
Bellman-FordO(V + VE)O(V + VE)Includes initialization even with no edges; signed edges and reachable-cycle detection.

Space

O(V) distance/frontier state for BFS, plus the input graph; other methods have their own heap/matrix costs.

Assumptions

  • The one-pass relaxation Lab illustrates an operation, not a complete general shortest-path algorithm.
  • Successful-relaxation snapshots add O(V) copying per reported update.

Invariants Worth Saying Aloud

  1. Every finite tentative distance is backed by a discovered path.
  2. A relaxation improves a target only through a reachable source.
  3. Only a method-specific ordering proof permits treating a tentative value as final.

When To Use Or Avoid Shortest Path

Use It When

  • Use BFS for unit edges, 0-1 BFS for binary costs, Dijkstra for nonnegative costs, and Bellman-Ford for signed edges.
  • Use topological relaxation on a weighted DAG, including negative edges.

Choose Another Tool When

  • A minimum spanning tree minimizes connection cost, not distances from a source.
  • A reachable negative cycle can make affected shortest-walk costs unbounded below.

Common Pitfalls

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

Adding through an unreachable source

None is not a numeric zero-cost path. Adding a weight to it raises TypeError.

Prevent it: Guard reachability before constructing a candidate.

Avoid

candidate = distance[source] + weight

Use instead

candidate = None if distance[source] is None else distance[source] + weight

Overwriting a cheaper path with a later expensive path

A discovered cost 4 should not be replaced by candidate 9. Relaxation minimizes rather than assigning every edge.

Prevent it: Update only if absent or strictly cheaper.

Avoid

distance[target] = candidate

Use instead

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

Confusing fewest edges with smallest total weight

A one-edge route can cost 8 while a two-edge route costs 3. Choosing fewer edges gives the wrong weighted answer.

Prevent it: Compare summed weights unless every edge has the same unit cost.

Avoid

chosen = min(routes, key=lambda route: route[0])

Use instead

chosen = min(routes, key=lambda route: route[1])

Reviewed References

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