Web Analytics

āš–ļø Bellman-Ford Algorithm

Advanced ~35 min read

Currency exchange rates can create arbitrage opportunities - if you can exchange currencies in a cycle and end up with more money than you started! Bellman-Ford algorithm detects such opportunities by finding negative cycles in graphs with negative weights.

The Negative Weight Problem

Dijkstra's fails with negative weights. Bellman-Ford handles them:

Real-World Applications

  • Currency Arbitrage: Detect profitable currency exchange cycles
  • Routing Protocols: Handle negative costs (rebates, discounts)
  • Negative Cycle Detection: Identify impossible/contradictory constraints
  • Network Protocols: Distance-vector routing (RIP, BGP)

How Bellman-Ford Works

Relaxation Process

  1. Initialize distances (start = 0, others = āˆž)
  2. Relax all edges V-1 times
  3. After V-1 iterations, distances should be optimal
  4. One more relaxation: If any edge can still be relaxed, negative cycle exists!

Key insight: After V-1 iterations, if we can still relax, there's a negative cycle!

See Bellman-Ford in Action

Negative Cycle Detection

Why V-1 Iterations?

In a graph with V vertices, shortest path has at most V-1 edges. After V-1 relaxations, all shortest paths should be found.

If we can still relax after V-1 iterations, it means there's a cycle with negative total weight!

The Complete Code

Output
Click Run to execute your code

Dijkstra vs Bellman-Ford

When to Use Each

Aspect Dijkstra Bellman-Ford
Time Complexity O((V+E) log V) O(VE)
Negative Weights No Yes
Negative Cycles Cannot detect Can detect
Best For Non-negative weights Any weights, need cycle detection

Currency Arbitrage Example

Convert exchange rates to graph: if you can exchange currencies in a cycle and end up with more money, there's a negative cycle (profitable arbitrage)!

Summary

What You've Learned

Bellman-Ford algorithm handles negative weights:

  1. Algorithm: Relax edges V-1 times, then check for cycles
  2. Time: O(VE) - Slower than Dijkstra
  3. Space: O(V)
  4. Advantage: Handles negative weights and detects negative cycles
  5. Applications: Currency arbitrage, routing protocols
  6. Key insight: If edges can still be relaxed after V-1 iterations, negative cycle exists

What's Next?

You've mastered Bellman-Ford! Next, we'll explore Minimum Spanning Tree (MST) - connecting all vertices with minimum total edge weight, perfect for network design and cluster analysis!