Skip to contentKEEP THE CRAFTTHE SANCTUARY

Bellman-Ford

Propagate shortest-path upper bounds through repeated signed-edge relaxation. Distinguish frozen previous-pass states from in-place updates, and detect only negative cycles reachable from the chosen source.

1 practice exercise2 interview problems

Recognize it when Edges may have negative weights and a source-specific negative-cycle report matters.

Checking your account…

Bellman-Ford Code Labs

Relax Every Edge Repeatedly

Any simple shortest path contains at most V minus one edges. Bellman-Ford performs enough full edge passes for improvements to propagate across paths of increasing edge count.

Stop Early When Nothing Changes

If an entire pass produces no improvement, all reachable shortest distances are already stable and later passes cannot change them.

Trace Bellman-Ford Passes

Reference
def bellman_passes(node_count,edges,start):
    distance=[None]*node_count;distance[start]=0;trace=[]
    for _ in range(node_count-1):
        changed=False;next_distance=distance.copy()
        for source,target,weight in edges:
            if distance[source] is not None:
                candidate=distance[source]+weight
                if next_distance[target] is None or candidate<next_distance[target]:next_distance[target]=candidate;changed=True
        distance=next_distance;trace.append(distance.copy())
        if not changed:break
    return trace
Practice

Implement bellman_passes(node_count,edges,start). Return distances after each full pass, using None for unreachable, and stop when unchanged. Require positive node_count, a valid start, and edge endpoints in 0..node_count-1.

Public tests

  • Propagate paths one edge farther per pass

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

Trace Bellman-Ford Passes

def bellman_passes(node_count,edges,start):
    distance=[None]*node_count;distance[start]=0;trace=[]
    for _ in range(node_count-1):
        changed=False;next_distance=distance.copy()
        for source,target,weight in edges:
            if distance[source] is not None:
                candidate=distance[source]+weight
                if next_distance[target] is None or candidate<next_distance[target]:next_distance[target]=candidate;changed=True
        distance=next_distance;trace.append(distance.copy())
        if not changed:break
    return trace

Advance a Signed Path One Edge per Frozen Pass

Predict the frozen-pass Lab on a four-node chain containing a negative edge. Its snapshot rule intentionally differs from the second in-place distance Lab, so do not infer exact pass rows from edge order alone.

Step Executed statement State Why
First pass next_distance=distance.copy() previous=[0,None,None,None] Only source 0 can contribute a candidate this pass.
Record first pass candidate=distance[source]+weight;next_distance[target]=candidate;distance=next_distance;trace.append(distance.copy()) after full pass: [0,4,None,None] The newly reached 1 cannot immediately feed edge 1->2 in a frozen pass.
Second pass next_distance=distance.copy();candidate=distance[source]+weight;next_distance[target]=candidate;distance=next_distance;trace.append(distance.copy()) after full pass: [0,4,2,None] The known cost 4 plus -2 reaches node 2.
Third pass next_distance=distance.copy();candidate=distance[source]+weight;next_distance[target]=candidate;distance=next_distance;trace.append(distance.copy()) after full pass: [0,4,2,5] A three-edge path is now represented within V-1 passes.
Print Output
print(bellman_passes(4, [[0, 1, 4], [1, 2, -2], [2, 3, 3]], 0)) [[0, 4, None, None], [0, 4, 2, None], [0, 4, 2, 5]]

For the cycle check, “negative” is not sufficient: the cycle must be reachable from the source. If a reachable negative cycle exists, affected shortest-walk costs have no finite minimum.

Detect Reachable Negative Cycles

After V minus one passes, one more successful relaxation from a reachable source proves a reachable negative cycle. Cycles in unreachable components do not invalidate source distances.

Compute Bellman-Ford Distances

Reference
def bellman_ford(node_count,edges,start):
    distance=[None]*node_count;distance[start]=0
    for _ in range(node_count-1):
        changed=False
        for source,target,weight in edges:
            if distance[source] is not None and (distance[target] is None or distance[source]+weight<distance[target]):distance[target]=distance[source]+weight;changed=True
        if not changed:break
    for source,target,weight in edges:
        if distance[source] is not None and (distance[target] is None or distance[source]+weight<distance[target]):return None
    return distance
Practice

Implement bellman_ford(node_count,edges,start). Return distances or None if a reachable negative cycle exists. Require positive node_count, a valid start, and edge endpoints in 0..node_count-1.

Public tests

  • Detect only reachable negative cycles

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

Compute Bellman-Ford Distances

def bellman_ford(node_count,edges,start):
    distance=[None]*node_count;distance[start]=0
    for _ in range(node_count-1):
        changed=False
        for source,target,weight in edges:
            if distance[source] is not None and (distance[target] is None or distance[source]+weight<distance[target]):distance[target]=distance[source]+weight;changed=True
        if not changed:break
    for source,target,weight in edges:
        if distance[source] is not None and (distance[target] is None or distance[source]+weight<distance[target]):return None
    return distance

Choose Bellman Ford or Dijkstra

Choose Bellman-Ford for possible negative edges and negative-cycle detection at O(V + VE), including initialization. Choose Dijkstra for nonnegative edges and better heap-based performance. DAGs permit one topological relaxation pass.

Explain It in an Interview

Say: “After pass i, paths using at most i edges are represented. V minus one covers every simple path; another improvement requires a reachable negative cycle.” Explain unreachable sentinels and early stopping.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Bellman-Ford with cycle checkO(V + VE)O(V + VE)O(V) initialization, up to V-1 passes, and a final O(E) reachable-cycle check; unchanged passes stop early.
Frozen-pass distance traceO(V * (V + E))O(V * (V + E))Each pass copies V distances before relaxation and into output. Early stopping can shorten the run; a reachable negative cycle can keep all bounded passes changing.

Space

O(V) distance storage beyond edges; frozen-pass trace stores up to O(V^2) cells.

Assumptions

  • The trace Lab reads a previous-pass table, so paths advance at most one edge per pass.
  • The in-place distance Lab can propagate multiple edges in one pass, depending on edge order; it is still guaranteed at least the frozen-pass progress.

Invariants Worth Saying Aloud

  1. Every finite value is the cost of a discovered source path.
  2. After i frozen passes, all paths of at most i edges are represented.
  3. After V-1 passes, an additional reachable improvement proves a reachable negative cycle.

When To Use Or Avoid Bellman-Ford

Use It When

  • Use Bellman-Ford when signed edges invalidate Dijkstra.
  • Stop early when a complete pass makes no change.

Choose Another Tool When

  • For nonnegative weights, heap Dijkstra is usually faster.
  • An unreachable negative cycle does not invalidate distances from this source.

Common Pitfalls

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

Making every vertex reachable with zero initialization

Initializing all distances to 0 allows an unrelated signed edge to create a fake source path.

Prevent it: Only the actual source begins at zero; other entries stay unreachable.

Avoid

distance = [0] * node_count

Use instead

distance = [None] * node_count
distance[start] = 0

Reading current-pass improvements in a frozen-pass trace

Using next_distance as a source table can cross two edges during one pass, violating the exact one-more-edge trace contract.

Prevent it: Read candidates from the unchanged previous distance table.

Avoid

candidate = next_distance[source] + weight

Use instead

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

Reporting an unreachable negative cycle

A negative self-loop at a node absent from source reachability must not reject this source’s result.

Prevent it: Require a reachable source before the extra relaxation/cycle check.

Avoid

negative_cycle = weight < 0

Use instead

negative_cycle = distance[node] is not None and weight < 0

Reviewed References

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