Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Shortest paths
EXPERIMENT 42 / 66

When a shortcut has a negative price.

Relax edges repeatedly and detect a reachable cycle that makes shortest distance undefined.

BY NAVAN SAMI◷ 9 MIN READSTRETCHALGORITHM

01 Model the idea

Bellman–Ford permits negative edge weights. After k full passes, every best path using at most k edges has been accounted for; in-place updates may also propagate farther within one pass. Any shortest simple path has at most V−1 edges. If a reachable distance can still improve afterward, a reachable negative cycle prevents finite shortest distances for affected destinations.

THE THING THAT MUST STAY TRUE

Distances are best-known upper bounds from valid discovered walks.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
INITIALISE source to zero and others to infinity
RELAX every edge up to V−1 times
CHECK for a further reachable improvement
A worked trace for this experiment
StageABC
Initial0∞∞
First full pass042
Converged042

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

bellman_ford.py
def bellman_ford(vertices, edges, start):
    distance = {node: float("inf") for node in vertices}
    distance[start] = 0
    for _ in range(len(vertices) - 1):
        changed = False
        for u, v, weight in edges:
            if distance[u] != float("inf") and distance[u] + weight < distance[v]:
                distance[v] = distance[u] + weight; changed = True
        if not changed: break
    for u, v, weight in edges:
        if distance[u] != float("inf") and distance[u] + weight < distance[v]:
            raise ValueError("Reachable negative cycle")
    return distance
print(bellman_ford(["A", "B", "C"], [("A", "B", 4), ("A", "C", 5), ("B", "C", -2)], "A"))
↳ EXPECTED OUTPUT
{'A': 0, 'B': 4, 'C': 2}
  1. 1

    Every edge considers a possible improvement through its source. Unreachable sources remain infinite and cannot establish a route.

  2. 2

    The early-exit flag stops when a full pass changes nothing. It does not change the worst-case O(VE) bound.

  3. 3

    The final pass detects a negative cycle reachable from the chosen source. A negative cycle elsewhere in a disconnected graph is not reported by this single-source check.

04 Count the cost

TIME

O(VE)

SPACE

O(V) distance state, excluding stored edges

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Detect a reachable negative cycle in a two-vertex example using the full relaxation rule.

Reveal one possible solution +
one_possible_solution.py
vertices = ["A", "B"]
edges = [("A", "B", 1), ("B", "A", -2)]
distance = {"A": 0, "B": float("inf")}
for _ in range(len(vertices) - 1):
    for u, v, w in edges: distance[v] = min(distance[v], distance[u] + w)
print(any(distance[u] + w < distance[v] for u, v, w in edges))

06 Check your reasoning

QUICK SIGNAL CHECK

What makes finite shortest distance impossible for affected vertices?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.