Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Bellman-Ford proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)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…
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.
If an entire pass produces no improvement, all reachable shortest distances are already stable and later passes cannot change them.
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 traceImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 tracePredict 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. |
| 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.
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.
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 distanceImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 distanceChoose 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.
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 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Bellman-Ford proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Bellman-Ford with cycle check | O(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 trace | O(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. |
O(V) distance storage beyond edges; frozen-pass trace stores up to O(V^2) cells.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
distance = [0] * node_countdistance = [None] * node_count
distance[start] = 0Where you will hit this: Relax Signed Edges with Bellman-Ford(opens in a new tab)
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.
candidate = next_distance[source] + weightcandidate = None if distance[source] is None else distance[source] + weightWhere you will hit this: Relax Signed Edges with Bellman-Ford(opens in a new tab)
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.
negative_cycle = weight < 0negative_cycle = distance[node] is not None and weight < 0Where you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27