Back to the 2025 paper

Module 3: Graph and Tree Algorithms

20257m

Explain how Bellman Ford algorithm can be used to detect the presence of negative weight cycles.

Worked SolutionAI Assisted

Bellman-Ford & Negative Weight Cycle Detection

Bellman-Ford Recap

Input: directed weighted graph G(V,E,w)G(V,E,w), source ss.

Init: dist[s]=0, dist[v]=∞ for v≠s
repeat V-1 times:
  for each edge (u,v) in E:
    if dist[u]+w(u,v) < dist[v]: dist[v]=dist[u]+w(u,v); parent[v]=u

After V−1V-1 iterations, dist[v]dist[v] = shortest path weight from ss using ≤ V−1V-1 edges (any simple path has ≤ V−1V-1 edges). Complexity O(VE)O(VE).

Detecting Negative Cycle

Extra VV-th iteration:

for each edge (u,v) in E:
  if dist[u]+w(u,v) < dist[v]: // still relaxable
    then v is reachable from a negative cycle (and from s)
    report "Negative cycle exists reachable from s"

Why? In graph without negative cycles, after V−1V-1 rounds no edge can be relaxed (shortest paths have converged). If an edge can still be relaxed, the shortest path would require ≥ VV edges → must repeat a vertex → contains a cycle. Since total weight decreased by going around cycle, that cycle is negative. Moreover, repeated relaxation can propagate −∞-\infty along all vertices reachable from the cycle.

Finding cycle: To retrieve cycle, follow parent pointers from vv VV times to get into cycle, then walk until repeat.

Example

Triangle s→as→a (1), a→ba→b (-2), b→ab→a (-2): sum b→a→bb→a→b = -4 negative. After V−1=2V-1=2 iterations dist keeps decreasing; Vth iteration detects relaxation.

Scope

  • Detects only cycles reachable from ss. To detect any negative cycle in graph, add super-source s′s' with 0-edge to all vertices and run Bellman-Ford.
  • Dijkstra cannot detect/develop must not be used with negatives.

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.