Pattern #59

Bellman-Ford Algorithm

Repeated edge relaxation, negative weights and cycles, limited-edge shortest paths, early stopping, reachability details, and Go templates.

Must Solve

10 core questions — solve these first.

  1. 1.Bellman-Ford Shortest Path
    medium
  2. 2.Detect Negative Cycle in Graph
    medium
  3. 3.Cheapest Flights Within K Stops
    medium
  4. 4.Network Delay Time — Compare with Dijkstra
    medium
  5. 5.Shortest Path with Negative Weights
    medium
  6. 6.Currency Arbitrage — Concept
    hard
  7. 7.Difference Constraints — Concept
    hard
  8. 8.Find the City With Smallest Number of Neighbors
    medium
  9. 9.Shortest Path in Directed Weighted Graph
    medium
  10. 10.Negative Cycle Reachability Problems
    hard

Also Important

5 advanced relations and optimizations.

  1. 11.Bellman-Ford with Path Reconstruction
    medium
  2. 12.Bellman-Ford with Early Stopping
    easy
  3. 13.Shortest Path with Maximum Number of Edges
    hard
  4. 14.SPFA — Practical Variant
    hard
  5. 15.Johnson's Algorithm — Advanced Relation
    hard

How to Think

Negative edge exists?Bellman-Ford
Need negative-cycle detection?Relax one extra round
At most K edges or stops?Limit the number of rounds
All weights non-negative?Usually prefer Dijkstra
Relax ALL edges
↓
Repeat V − 1 times
↓
One extra round
↓
Any reachable improvement = negative cycle

Go Quick Reference — Bellman-Ford

type Edge struct { from, to int; weight int64 }

func bellmanFord(n int, edges []Edge, start int) ([]int64, bool) {
    dist := make([]int64, n)
    for i := range dist { dist[i] = INF }
    dist[start] = 0
    for round := 1; round < n; round++ {
        changed := false
        for _, e := range edges {
            if dist[e.from] == INF { continue }
            cand := dist[e.from] + e.weight
            if cand < dist[e.to] { dist[e.to], changed = cand, true }
        }
        if !changed { break }
    }
    for _, e := range edges {
        if dist[e.from] != INF && dist[e.from]+e.weight < dist[e.to] {
            return dist, true
        }
    }
    return dist, false
}

A shortest simple path uses at most V − 1 edges, so each full pass can propagate correct distance information one edge farther.

Key Variants

K Stops

Copy the previous distance array each round so one round cannot accidentally use multiple new edges. K stops permits K + 1 edges.

Negative Cycle Reachability

For source shortest paths, relax only from reachable nodes. A disconnected negative cycle does not affect the source.

Path Reconstruction

Update parent[v] whenever dist[v] improves; do not report a finite shortest route through an affected negative cycle.

Bellman-Ford as DP

After round i, distances represent best paths using at most i edges—exactly the state behind limited-flight problems.

Visual Memory Rule
Relax ALL edges → one round
Repeat V − 1 rounds → shortest simple paths
No update → stop early
One more improvement → reachable negative cycle

Complexity

Time:  O(VE)
Space: O(V)
Edge list storage: O(E)
Early stopping: often faster, worst case remains O(VE)

Common Interview Mistakes

• Forgetting the dist[u] != INF reachability guard

• Running only one edge pass

• Skipping the extra negative-cycle pass

• Miscounting K stops versus K + 1 edges

• Updating in place when rounds must limit edges

• Treating every negative cycle as source-relevant

• Using Bellman-Ford on a DAG instead of topological relaxation

Interview Rules

Negative edge       → Bellman-Ford
Normal rounds       → V − 1
Negative cycle      → improvement on extra round
Unreachable node    → never relax from INF
At most K edges     → K copied rounds
No update in a pass → stop early
DAG                 → topological shortest path

Production Thinking

Discounts and credits → negative edges model rebates without implying a negative cycle.

Currency arbitrage → -log(rate) turns profitable cycles into negative cycles.

Production warning → O(VE) is expensive; prefer Dijkstra for non-negative weights or topological relaxation for DAGs.

Remember This

Bellman-Ford → negative edges
Representation → edge list
Rounds → V − 1
Extra round → negative cycle
Reachability guard → dist[u] != INF
Early stop → no update
Time → O(VE)

💡 Golden Rule: Relax every edge repeatedly; if a reachable distance still improves after V − 1 rounds, a negative cycle is present.