Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 13  /  BELLMAN-FORD

The Patient Router.

Watch the explainer

Dijkstra is fast but proud — one negative edge and it's wrong. Bellman-Ford is patient: it relaxes every edge again and again until the numbers stop moving, so it finds the shortest paths even with negative weights — and spots a negative cycle when one exists.

THE GIST · 20 SECONDS

Bellman-Ford finds shortest paths from one source. Start every distance at ∞ (source = 0), then relax every edge — if dist[u]+w < dist[v], lower dist[v] — and repeat the whole sweep V − 1 times. After that the distances are final. One extra pass that still improves anything means a negative cycle. Slower than Dijkstra, but it survives negatives.

  • Relaxtry a shorter route to v
  • Sourcewhere distance = 0
  • V − 1 passeslongest path has V−1 edges
  • Neg cyclestill improving = trap

Hit Step to relax the next edge — or Play and watch the distances ripple out from the source and settle.

UNDER THE HOOD

What you just played, written down

One operation — relax — repeated until nothing changes. No priority queue, no assumptions about signs. Just patience, and a clever bound on how many passes you need.

How Bellman-Ford thinks — four moves

  1. Seed the distances. dist[source] = 0, everyone else ∞. We only know we can stay put for free.
  2. Relax every edge. For each (u, v, w): if dist[u] + w < dist[v], we found a shorter way — lower dist[v].
  3. Repeat V − 1 times. A shortest path has at most V − 1 edges, so V − 1 full sweeps lock in every one.
  4. One more pass = the alarm. If any edge still relaxes, distances never settle — a negative cycle is reachable.
WHY DIJKSTRA CAN'T DO THIS

Dijkstra commits a node's distance the moment it's popped, betting no later path is cheaper. A negative edge can make a later path cheaper, breaking that bet. Bellman-Ford commits to nothing until V − 1 passes are done.

The whole thing in code

def bellman_ford(n, edges, src):   # edges: [u, v, w]
    dist = [float('inf')] * n
    dist[src] = 0
    # relax every edge V-1 times
    for _ in range(n - 1):
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
    # one more pass: still improving = negative cycle
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            return None            # negative cycle!
    return dist
TIMEO(V·E)V−1 passes × E edges
SPACEO(V)one distance per node
IT'S DYNAMIC PROGRAMMING

Pass k computes the shortest path using at most k edges. Each pass builds on the last — the same "solve by edge count" recurrence you'd write as a DP table, run in place over the distance array.

⚠ Negative cycle = no answer

If a reachable cycle has negative total weight, you can loop it forever to make paths shorter without bound — so "shortest path" is undefined. Bellman-Ford's job there is to detect it, not to return a distance.

↔ Early exit & SPFA

If a full pass changes nothing, you can stop early — the distances are final. The SPFA variant only re-relaxes edges out of recently-updated nodes, often much faster in practice.

★ Where it's used

Currency arbitrage (a negative cycle = free money), routing protocols (distance-vector / RIP), and as the first stage of Johnson's all-pairs shortest paths.

The picture: the tree of settled distances

6758−4−39−227A0B2C4D7E−2accent = shortest-pathtree: A → D → C → B → Enumber under node =final distance from A
The page’s five-node graph with its final distances from A. The accent edges form the shortest-path tree: A → D → C → B → E, whose weights 7, −3, −2, −4 total −2. The cheapest route to B is not the direct edge of weight 6 but the longer one through D and C, which is what Dijkstra’s greedy rule would miss.

Worked example, step by step

Source A, edges processed in the order the page lists them: A→B 6, A→D 7, B→C 5, B→D 8, B→E −4, D→C −3, D→E 9, C→B −2, E→A 2, E→C 7. The table shows every relaxation that succeeded. Edges that did not lower anything are skipped.

PassEdge (w)RelaxationDistances [A, B, C, D, E]
0start—[0, ∞, ∞, ∞, ∞]
1A→B (6)0 + 6 = 6[0, 6, ∞, ∞, ∞]
1A→D (7)0 + 7 = 7[0, 6, ∞, 7, ∞]
1B→C (5)6 + 5 = 11[0, 6, 11, 7, ∞]
1B→E (−4)6 − 4 = 2[0, 6, 11, 7, 2]
1D→C (−3)7 − 3 = 4[0, 6, 4, 7, 2]
1C→B (−2)4 − 2 = 2[0, 2, 4, 7, 2]
2B→E (−4)2 − 4 = −2[0, 2, 4, 7, −2]
3all 10 edgesno change[0, 2, 4, 7, −2]: stop

Notice the order inside pass 1. B was first set to 6, then lowered to 2 only when C→B ran, near the end of the pass, and E was set from the old B. Pass 2 repairs it: B→E now gives 2 − 4 = −2. Pass 3 changes nothing, so the loop can stop after three of the four allowed passes. A final detection pass would also find nothing, so there is no negative cycle even though the graph has negative edges, and the graph does contain the cycle B→C→B of weight 5 − 2 = +3, which is harmless. Dijkstra on the same graph ends with [0, 6, 4, 7, 2], wrong for B and E.

Complexity and trade-offs

CaseTimeSpaceWhy
Bellman-FordO(V · E)O(V)V − 1 passes over E edges. Here that is at most 4 × 10 = 40 edge checks; early exit stopped after 3 × 10 = 30.
Bellman-Ford, best case with early exitO(E)O(V)One pass that changes things plus one that confirms. A path listed in forward order settles in 2 passes; the same path listed backwards needs 5.
Dijkstra (binary heap)O((V + E) log V)O(V)Much faster, but only correct with non-negative weights.
DAG relaxation in topological orderO(V + E)O(V)Handles negative weights, but only on acyclic graphs.
Floyd-WarshallO(V³)O(V²)All pairs at once, negative edges allowed; worth it only for small, dense graphs.

Bellman-Ford is the price you pay for negative edges on a general graph, and the extra pass that detects negative cycles comes free. Its relaxation passes are also independent of the order of edges inside a pass for correctness, though not for speed, so shuffling or sorting the edge list changes how soon it stops, never what it returns, provided there is no negative cycle.

Common mistakes

  • Relaxing out of an unreachable node

    With a large integer standing in for infinity, INF + w is smaller than INF when w is negative. In a 4-node test with edges 0→1 (4) and 2→3 (−10), node 3 is unreachable, but a sentinel of 10⁹ without a guard gives it a distance of 999999990 instead of “unreachable”. Check dist[u] != INF before relaxing.

  • Running too few passes

    The bound is V − 1 passes, not V − 2. A path of 6 nodes with its edges listed backwards needs all 5; with only 4 passes the last node is still ∞ instead of 5.

  • Skipping the detection pass

    With the cycle 1→2 (−3), 2→1 (1) reachable from 0, distances never settle. Node 2 reads −4 after 2 passes and −40 after 20. Without the extra pass the code returns a confident-looking number that is simply wherever it stopped.

  • Using Dijkstra on negative edges

    On this page’s graph, a Dijkstra that settles each node once returns [0, 6, 4, 7, 2]. The correct answer is [0, 2, 4, 7, −2], so B and E are both wrong. Once a node is settled, a later negative edge can still make it cheaper.

  • Adding an undirected negative edge

    An undirected edge of weight −1 is really two directed edges, 0→1 and 1→0, and together they form a negative cycle. Bellman-Ford reports it correctly. The mistake is feeding it a graph you thought was undirected and expecting a distance.

Where this shows up

  • Distance-vector routing

    Routers that exchange distance tables with their neighbours and update their own are doing Bellman-Ford’s relaxation in a distributed way, one hop of information per round.

  • Currency arbitrage

    Taking the negative logarithm of each exchange rate turns a profitable loop into a negative cycle, which the extra pass finds. The weights are then sums of logs, so exactness depends on rounding.

  • Difference constraints

    A system of constraints of the form x − y ≤ c is feasible exactly when its constraint graph has no negative cycle, and the shortest distances from a virtual source are a solution.

  • Inside other algorithms

    Johnson’s all-pairs method runs Bellman-Ford once to re-weight a graph so Dijkstra can then be used from every source.

SOLVE IT YOURSELF

Solve it: single-source shortest paths

This one is yours to write — in Python or TypeScript, running for real in your browser. Relax every edge V-1 times and return the distances. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement bellman_ford(n, edges, src): n nodes (0…n-1), directed edges as [u, v, w]. Return the list of shortest distances from src (use a large number / infinity for unreachable). Assume no negative cycle for the returned distances.

HINTS — 4 IDEAS
  1. Init dist = [inf]*n, then dist[src] = 0.
  2. Repeat n-1 times: for every edge (u,v,w), if dist[u]+w < dist[v], set dist[v] = dist[u]+w.
  3. Guard against inf + w: only relax when dist[u] is finite (not infinity).
  4. Return dist — the shortest distance from src to each node.
CPython · WebAssembly
▶  Watch it explained

Bellman-Ford: Time and Space Complexity, From First Principles

QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. Why can Bellman-Ford handle negative edge weights when Dijkstra can’t?

    Answer: It never commits a distance early — it re-relaxes every edge V-1 times — Dijkstra finalizes a node when popped, assuming no cheaper path appears later — a negative edge breaks that. Bellman-Ford keeps relaxing every edge across V-1 passes, so a later, cheaper path still gets picked up.

  2. Why does the algorithm run exactly V-1 relaxation passes?

    Answer: Because a shortest path uses at most V-1 edges — A simple shortest path can’t repeat a node, so it has at most V-1 edges. Each pass finalizes shortest paths of one more edge, so V-1 passes finalize them all.

  3. How does Bellman-Ford detect a negative cycle?

    Answer: If one extra pass after V-1 rounds still relaxes some edge — After V-1 passes distances should be final. If a V-th pass can still lower a distance, paths keep shrinking — only possible with a reachable negative-weight cycle.

FAQ

Bellman-Ford, answered

What is Bellman-Ford?

A single-source shortest-path algorithm that works with negative edge weights. It relaxes every edge V − 1 times until the distances settle, and can detect a negative cycle with one extra pass.

What does relaxing an edge mean?

For edge (u, v, w): if dist[u] + w < dist[v], a shorter route to v exists, so set dist[v] = dist[u] + w. That single check, repeated, is the whole algorithm.

Why V − 1 passes?

A shortest path visits each node at most once, so it uses at most V − 1 edges. Each pass finalizes shortest paths of one more edge, so V − 1 passes finalize them all.

How does it detect a negative cycle?

After V − 1 passes the distances should be final. If one more pass still relaxes an edge, distances never converge — a reachable negative-weight cycle exists.

Bellman-Ford vs Dijkstra?

Dijkstra is faster (O((V+E) log V)) but needs non-negative weights. Bellman-Ford is slower (O(V·E)) but handles negatives and detects negative cycles.

RESULT

—

Next → drop the negative weights and commit each node as you pop it from a priority queue — that's Dijkstra's algorithm, faster but sign-sensitive.

Finished this one? 0 / 99 Algorithms done
NextEvery Vertex a Stepping Stone: Floyd–Warshall Next on the “The cheapest way across” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms