What is Bellman-Ford algorithm?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Bellman-Ford finds the shortest path from a source to all vertices in a weighted graph, including graphs with negative weight edges. It can also detect negative weight cycles (where Dijkstra fails). Algorithm: (1) Initialize distances: source = 0, all others = ∞; (2) Repeat V-1 times: relax all edges — for each edge (u,v,w): if dist[u] + w < dist[v], update dist[v]; (3) Check for negative cycles: run one more relaxation pass — if any distance can still be reduced, a negative cycle exists. Time: O(V×E). Space: O(V). Why V-1 iterations: the shortest path in a graph with V nodes has at most V-1 edges. If it still improves on the Vth pass, there's a negative cycle. Bellman-Ford vs Dijkstra: Bellman-Ford handles negative weights; Dijkstra doesn't but is faster (O((V+E)logV) vs O(VE)). SPFA (Shortest Path Faster Algorithm): queue-based Bellman-Ford optimization — processes only vertices whose distances changed. Average O(E), worst O(VE). Applications: (1) Network routing (RIP protocol); (2) Currency arbitrage detection (negative cycle = profitable arbitrage); (3) Constraint satisfaction; (4) Negative weight graphs. Bellman-Ford and Dijkstra are the two fundamental single-source shortest path algorithms.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Data Structures & Algorithms answers easy to follow.