DSA Notes
Master Bellman-Ford algorithm completely — why it handles negative weights where Dijkstra fails, the V-1 relaxation rounds, negative cycle detection, SPFA optimization, comparison with Dijkstra, and applications in currency arbitrage and network routing protocols.
Why Bellman-Ford Exists
Dijkstra's algorithm fails with negative edge weights. Bellman-Ford is the solution — it handles negative weights correctly and also detects negative cycles (cycles where the total weight is negative, making shortest path undefined).
| Graph: A | B (weight=4) |
| A | C (weight=2) |
| C | B (weight=-3) ← NEGATIVE! |
| Dijkstra | processes A, extracts B with dist=4 (wrong!) |
| Bellman-Ford: correctly finds A | C→B = 2 + (-3) = -1 |
Algorithm
Why V-1 iterations? The shortest path in a graph with V vertices has at most V-1 edges. After V-1 relaxations, all shortest paths are found (if no negative cycle exists). If a V-th iteration still finds a shorter path, a negative cycle is reachable.
Complete Implementation
Step-by-Step Trace
| n=4 vertices, edges: (0 | 1,4),(0→2,2),(2→1,-3),(1→3,1),(2→3,5) |
| Initial | dist = [0, ∞, ∞, ∞] |
| (0 | 1, 4): dist[0]+4=4 < ∞ → dist[1]=4 |
| (0 | 2, 2): dist[0]+2=2 < ∞ → dist[2]=2 |
| (2 | 1,-3): dist[2]+(-3)=-1 < 4 → dist[1]=-1 |
| (1 | 3, 1): dist[1]+1=0 < ∞ → dist[3]=0 |
| (2 | 3, 5): dist[2]+5=7 > 0 → no update |
| After round 1 | dist = [0, -1, 2, 0] |
| No edge improves any distance | all converged |
| Final | dist = [0, -1, 2, 0] ✓ |
| No edge improves any distance | no negative cycle ✓ |
Negative Cycle Detection and Reporting
SPFA — Shortest Path Faster Algorithm
SPFA is an optimization of Bellman-Ford using a queue. Instead of relaxing ALL edges in each round, only relax edges from vertices whose distance was recently updated.
Why SPFA is faster in practice:
- Only vertices with updated distances re-enter the queue
- On sparse graphs with no negative cycles, most vertices enter the queue O(1) times
- Degenerates to O(VE) only on adversarial graphs
Bellman-Ford on Directed Graphs with All-Pairs
def bellman_ford_all_pairs(edges, n):
"""
Run Bellman-Ford from all vertices to get all-pairs shortest paths.
Time: O(V² × E) — much slower than Floyd-Warshall O(V³) for dense graphs.
But better for very sparse graphs.
"""
all_dist = []
for source in range(n):
dist, has_neg = bellman_ford(edges, n, source)
all_dist.append(dist)
return all_distApplication — Currency Arbitrage Detection
Bellman-Ford vs Dijkstra
| Feature | Dijkstra | Bellman-Ford |
|---|---|---|
| Negative weights | ❌ Fails | ✅ Handles |
| Negative cycles | ❌ Doesn't detect | ✅ Detects |
| Time complexity | O((V+E) log V) | O(V × E) |
| Algorithm type | Greedy | Dynamic programming |
| Best for | Non-negative weights | Any weights, including negative |
| Directed/Undirected | Both | Both |
Summary
Bellman-Ford: relax all edges V-1 times, detect negative cycles in V-th round.
- Time: O(V×E) — slower than Dijkstra but handles negatives
- Negative cycle detection: V-th round finds any remaining improvements
- SPFA: Queue-based optimization — O(E) average case
- Use when: Negative edges present, negative cycle detection needed, distributed settings (Bellman-Ford is the basis of RIP routing protocol)
*Next Lesson: Floyd-Warshall Algorithm*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Bellman-Ford Algorithm — Shortest Path with Negative Weights and Cycle Detection.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, graphs, bellman, ford
Related Data Structures & Algorithms Topics