SnapDevCode

Bellman-Ford Algorithm

LeetCode #787
Presets:
Start NodeA
Pass CounterInit
Target NodeF
Dist to Target
Step 1 / 0
Ready to compute Bellman-Ford shortest paths.
42-123452-33A0STARTBCDEFTARGET
Start:Target:
Path: Calculating...
Code Execution

💡 Bellman-Ford in Layman's Terms

Bellman-Ford is like Google Maps finding the cheapest driving route with toll discounts & cashbacks! Unlike Dijkstra (which fails when discounts appear later), Bellman-Ford checks every road repeatedly to guarantee the best price.

How it Works in 4 Simple Steps:
  • 1Set Start to $0: Starting city cost = $0, all other cities = ∞ (Unknown).
  • 2Check Every Road in Passes: If dist[u] + weight < dist[v], take the shortcut and update dist[v]!
  • 3Repeat (V - 1) Times: Guarantees finding shortcuts up to V - 1 hops away.
  • 4Pass V Cycle Check: Check one last time. If any distance still drops, you found an infinite cashback loop (Negative Cycle)!
🚗 Real-World Analogy: Toll Discounts & Infinite Loops

If a toll highway offers a cashback coupon, Bellman-Ford factors it in. But if a circular ring-road gives you $5 cashback every lap, looping forever would give infinite profit (-∞). Bellman-Ford catches this glitch during Pass V!

Distance Vector (dist[])Idle
NodeKnown DistancePrevious HopStatus
ASTART0Reachable
BUnvisited
CUnvisited
DUnvisited
EUnvisited
FUnvisited
Time: O(V · E)Space: O(V)
LeetCode #787
Algorithm Masterclass

Mastering the Bellman-Ford Shortest Path Algorithm

The Bellman-Ford algorithm is a dynamic programming powerhouse designed to compute Single-Source Shortest Paths (SSSP) on weighted directed graphs. Unlike greedy alternatives like Dijkstra, Bellman-Ford safely handles negative edge weights and definitively detects negative weight cycles.

Negative Edge Weight Handling

Dijkstra makes permanent greedy commitments that fail when negative shortcuts appear later. Bellman-Ford repeatedly relaxes all edges, guaranteeing optimal distances even with negative tolls or voucher discounts.

Negative Cycle Detection (Pass V)

If a graph has a cycle whose net sum of edge weights is negative, shortest paths are theoretically -∞. Bellman-Ford detects this during pass V if any edge can still be relaxed.

Forex Currency Arbitrage

In financial currency exchange markets, converting exchange rates via -log(rate) transforms multiplicative exchange yields into additive shortest paths, allowing algorithmic traders to detect arbitrage loops instantly.

The Concrete Proof: Why Exactly \(|V| - 1\) Loops Are Required

Understanding the worst-case edge relaxation propagation through a concrete example:

Consider a simple line graph with 4 nodes and edge weights of 1:

(A)1(B)1(C)1(D)

Initially: dist[A] = 0 and dist[B] = ∞, dist[C] = ∞, dist[D] = ∞.

In Bellman-Ford, a "loop" iterates through every edge in our edge array. But we cannot guarantee the ordering of edges in memory! Suppose the edges are stored in the absolute worst-case order (Right-to-Left):

Edge Array Order: [ Edge(C ➔ D), Edge(B ➔ C), Edge(A ➔ B) ]
Loop #Edge InspectedRelaxation ConditionResultDistances at End of Loop
Loop 1C ➔ Ddist[C] is ∞ + 1 = ∞ ≮ ∞No change (D = ∞)A: 0, B: 1, C: ∞, D: ∞
B ➔ Cdist[B] is ∞ + 1 = ∞ ≮ ∞No change (C = ∞)
A ➔ Bdist[A] is 0 + 1 = 1 < ∞⚡ B updated to 1!
Loop 2C ➔ Ddist[C] is still ∞No change (D = ∞)A: 0, B: 1, C: 2, D: ∞
B ➔ Cdist[B] is 1 + 1 = 2 < ∞⚡ C updated to 2!
A ➔ B0 + 1 = 1 == 1Already optimal
Loop 3 (V - 1)C ➔ Ddist[C] is 2 + 1 = 3 < ∞⚡ D updated to 3!A: 0, B: 1, C: 2, D: 3
B ➔ C1 + 1 = 2 == 2Already optimal
A ➔ B0 + 1 = 1 == 1Already optimal
💡 The Core Takeaway:

In the worst-case edge order, each loop can only advance the shortest path "wave" by exactly 1 edge forward. Since the longest simple path in a graph with \(V\) vertices has \(V - 1\) edges, we strictly require \(|V| - 1\) loops to guarantee that all vertices have received their optimal shortest distance!

Shortest Path Algorithm Showdown: Bellman-Ford vs. Dijkstra vs. Floyd-Warshall

When to use each algorithm in technical interviews and system design:

AlgorithmScopeTime ComplexityNegative Weights?Negative Cycle Detection?
Bellman-FordSingle-Source (1 to All)O(V · E)✅ Yes✅ Yes (Pass V)
Dijkstra (Min-Heap)Single-Source (1 to All)O((V + E) log V)❌ No (Non-negative only)❌ No (May infinite loop)
Floyd-WarshallAll-Pairs (All to All)O(V³)✅ Yes✅ Yes (Check dist[i][i] < 0)
BFS (Unweighted)Single-Source (1 to All)O(V + E)N/A (Unweighted only)N/A

LeetCode & Technical Interview Preparation Advice

1. LeetCode #787: Cheapest Flights Within K Stops

Direct Bellman-Ford variant! Instead of V - 1 passes, run exactly k + 1 passes with an immutable copy of distances per pass.

2. Early Termination Optimization (SPFA)

Keep a boolean flag updated per pass. If 0 edges are relaxed, terminate immediately to save unnecessary O(V · E) cycles.

3. Distance Copying for K-Stops

When solving constrained hop problems, always clone temp_dist = dist[:] before each pass to prevent multi-hop cascades in a single iteration.

4. Distributed Routing Protocols (RIP)

Routing Information Protocol (RIP) uses Bellman-Ford in network routers where each router shares distance vectors with immediate neighbors.

Frequently Asked Questions (FAQ)

Key interview questions on Bellman-Ford:

Why does Dijkstra fail on graphs with negative edge weights?

Dijkstra greedily marks a node as permanently visited the moment it is extracted from the priority queue, assuming no future path can be shorter. If a negative weight edge appears later, Dijkstra cannot backtrack to update already locked nodes, resulting in incorrect shortest distances.

What is a Negative Weight Cycle?

A directed cycle whose total sum of edge weights is strictly negative (< 0). By continuously looping around this cycle, you can reduce the path length to -∞. Hence, no finite shortest path exists.

What is the Time and Space Complexity of Bellman-Ford?

Time Complexity: O(V · E) because we perform at most V-1 passes over all E edges.
Space Complexity: O(V) to store the distance array and predecessor map.