Introduction
In our last lesson, we mastered Dijkstra's algorithm for finding the shortest path in graphs with non-negative edge weights. We established that its greedy approach, which finalizes the shortest path to the nearest unvisited node, is highly efficient. However, we concluded with a critical question: what happens if a graph contains negative edge weights?
This lesson directly addresses that challenge. You will learn to solve single-source shortest path problems in the presence of negative weights using the Bellman-Ford algorithm. This algorithm is more robust than Dijkstra's and can handle a wider variety of graphs. A key aspect of our study will be framing Bellman-Ford as a Dynamic Programming solution, which should provide valuable practice in an area you've identified for improvement.
Furthermore, we will analyze a fascinating consequence of negative weights: the negative weight cycle. You'll learn how Bellman-Ford not only finds shortest paths but can also detect these cycles, where the concept of a "shortest" path breaks down entirely.
When Greed Fails: The Problem with Negative Weights
Dijkstra's greedy strategy works because once it declares the shortest path to a node, it assumes no future path will be shorter. This assumption holds only if adding an edge can never decrease a path's total weight.
With negative edges, this guarantee is broken. A path that currently seems long could suddenly become the shortest by traversing a later edge with a large negative weight. Dijkstra's, having already committed to a different path, would miss this opportunity.
A classic real-world analogy is currency arbitrage. Imagine converting currencies where edge weights are −log(exchange_rate). A path that returns to the starting currency with a negative total weight represents a profitable arbitrage opportunity—a negative cycle. Dijkstra's algorithm cannot find these.
4.4 Bellman Ford Algorithm - Single Source Shortest Path - Dynamic Programming
To start, let's watch a brief segment that clearly articulates why Dijkstra's fails and where Bellman-Ford fits in. It also introduces its connection to dynamic programming.
Watch from the beginning to 01:10. Focus on the explanation of why a new algorithm is needed when negative edges are present and note the mention of its 'dynamic programming strategy'.
The Bellman-Ford Algorithm: A Dynamic Programming Perspective
Instead of a greedy approach, Bellman-Ford uses a systematic, iterative method that builds upon solutions to smaller subproblems—the hallmark of dynamic programming.
Let's define dist(i, v) as the length of the shortest path from the source node s to a vertex v that uses at most i edges.
Our base case is dist(0, s) = 0 and dist(0, v) = ∞ for all other vertices v.
For each subsequent step i (from 1 to n-1, where n is the number of vertices), the shortest path to v with at most i edges can be one of two things:
- The shortest path to
vthat we already found using at mosti-1edges. - A new, shorter path formed by taking the shortest path to some neighbor
uusing at mosti-1edges, and then traversing the edge(u, v).
This gives us the Bellman-Ford recurrence relation:
This may look complex, but it simplifies to a very practical algorithm: for n-1 iterations, we "relax" every edge in the graph.
Edge Relaxation
Relaxing an edge (u, v) with weight w is the core operation. It means checking if the path to v can be improved by going through u.

The Bellman-Ford algorithm repeatedly applies this relaxation to all edges in the graph.
Let's watch a detailed walkthrough of this iterative relaxation process. This video demonstrates how the distances are progressively updated over multiple passes.
Watch the segment from 04:48 to 14:39. Observe how the algorithm iterates through a fixed list of edges multiple times. Pay close attention to how a distance updated in one iteration can lead to further updates for its neighbors in the next iteration.
Here is a static view of the process, showing the distance table's state after each full iteration.

Staff-Level Intuition: Why n-1 Iterations?
A crucial question for a senior interview is why exactly n-1 iterations are sufficient.
In a graph with n vertices, any simple path (a path without cycles) can have at most n-1 edges. The Bellman-Ford algorithm guarantees that after the i-th iteration, it has found the shortest path to all nodes that can be reached using at most i edges.
Therefore, after n-1 iterations, it must have found the shortest simple path to all reachable nodes.
The following video provides an excellent, intuitive proof for why n-1 iterations are the magic number. It uses a worst-case scenario to make the reasoning clear.
Watch carefully from 16:03 to 21:13. The presenter constructs a 'chain' graph where the shortest path information propagates one step at a time, demonstrating the necessity of n-1 passes in the worst case.
For a more formal proof, you can review the "The proof of the algorithm" section in the CP-Algorithms article (LINK). This article provides a rigorous argument based on the path length, which complements the video's intuition.
Detecting Negative Weight Cycles
What if a graph contains a cycle whose edges sum to a negative value? You could traverse this cycle infinitely, making the path length arbitrarily small (-∞). In this case, a "shortest path" is undefined.
Bellman-Ford has a simple and elegant way to detect this. We've established that after n-1 iterations, all shortest simple paths are found. If we perform one more iteration (the n-th iteration) and any distance can still be relaxed, it proves the existence of a negative weight cycle. A further relaxation is only possible if the optimal path isn't simple, meaning it must contain a cycle that continues to reduce the total path cost.
Bellman-Ford - The case of a negative cycle
The CP-Algorithms article clearly explains this detection mechanism. It also provides an implementation for finding and outputting the cycle itself, a common interview follow-up.
Read the sections 'The case of a negative cycle' and its 'Implementation'. Focus on the criterion for detection: if a relaxation occurs in the n-th phase, a negative cycle exists.
Go Implementation and Analysis
The implementation of Bellman-Ford is more straightforward than Dijkstra's because it doesn't require a priority queue. It consists of nested loops: an outer loop for the iterations and an inner loop that iterates over all edges.
Go Code
Here is a Go implementation that finds the shortest paths and also detects negative cycles.
package main
import (
"fmt"
"math"
)
// Edge represents a directed edge with a weight.
type Edge struct {
From int
To int
Weight int
}
// BellmanFord finds shortest paths from a source in a graph with V vertices.
// It returns distances, predecessors, and a boolean indicating if a negative cycle was found.
func BellmanFord(edges []Edge, V, source int) (map[int]int, map[int]int, bool) {
distances := make(map[int]int)
predecessors := make(map[int]int)
for i := 0; i < V; i++ {
distances[i] = math.MaxInt32
predecessors[i] = -1 // -1 indicates no predecessor
}
distances[source] = 0
// 1. Relax edges for V-1 iterations
for i := 0; i < V-1; i++ {
for _, edge := range edges {
if distances[edge.From] != math.MaxInt32 && distances[edge.From]+edge.Weight < distances[edge.To] {
distances[edge.To] = distances[edge.From] + edge.Weight
predecessors[edge.To] = edge.From
}
}
}
// 2. Check for negative weight cycles (V-th iteration)
for _, edge := range edges {
if distances[edge.From] != math.MaxInt32 && distances[edge.From]+edge.Weight < distances[edge.To] {
return nil, nil, true // Negative cycle detected
}
}
return distances, predecessors, false
}
func main() {
V := 5
source := 0
edges := []Edge{
{0, 1, -1}, {0, 2, 4},
{1, 2, 3}, {1, 3, 2}, {1, 4, 2},
{3, 2, 5}, {3, 1, 1},
{4, 3, -3},
}
distances, _, hasNegCycle := BellmanFord(edges, V, source)
if hasNegCycle {
fmt.Println("Graph contains a negative weight cycle")
} else {
fmt.Println("Shortest distances from source", source)
for i := 0; i < V; i++ {
fmt.Printf("Vertex %d: %d\n", i, distances[i])
}
}
}
Complexity Analysis
- Time Complexity:
The algorithm has an outer loop that runsVtimes (V-1 for path calculation, 1 for cycle detection). The inner loop iterates through allEedges. This gives a straightforward time complexity of . - Space Complexity:
We need to store distances and predecessors for allVvertices.
Discussion: Bellman-Ford vs. Dijkstra
This is a classic interview trade-off discussion.
- Dijkstra: Faster at , but less general (requires non-negative weights).
- Bellman-Ford: Slower at , but more robust—it handles negative weights and can detect negative cycles.
In an interview, you'd choose Dijkstra's if you can guarantee non-negative weights (e.g., physical distances, time). You'd use Bellman-Ford if weights could be negative (e.g., financial gains/losses, arbitrage).
Conclusion
In this lesson, we expanded our shortest-path toolkit to handle graphs with negative edge weights. We saw how Dijkstra's greedy approach fails in this scenario and how the Bellman-Ford algorithm provides a robust, dynamic programming-based solution.
Key Takeaways:
- Bellman-Ford finds single-source shortest paths in graphs that may contain negative weight edges.
- Its core mechanic is to relax all
EedgesV-1times. This is a direct application of a dynamic programming recurrence. - It can detect negative weight cycles by performing a
V-th iteration; if any path is further improved, a negative cycle exists. - The time complexity is , which is slower than Dijkstra's, representing a trade-off between speed and generality.
- An interesting optimization is the Shortest Path Faster Algorithm (SPFA), which uses a queue to only relax edges from vertices whose distances have recently changed. While its worst-case complexity remains , it is often much faster in practice. Being aware of SPFA demonstrates a deeper knowledge of the topic.
We have now seen how to detect a specific kind of cycle—one with a negative total weight. In our next lesson, we will broaden our scope to detect any cycle in a graph, a fundamental problem in areas like dependency resolution and deadlock detection, using a completely different approach: Depth-First Search.