VOOZH about

URL: https://www.geeksforgeeks.org/dsa/detect-negative-cycle-graph-bellman-ford/

โ‡ฑ Detect a negative cycle in a Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Detect a negative cycle in a Graph

Last Updated : 29 Apr, 2026

Given a directed weighted graph, your task is to find whether the given graph contains any negative cycles that are reachable from the source vertex (e.g., node 0).

Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.

Examples:

Input: V = 4, edges[][] = [[0, 3, 6], [1, 0, 4], [1, 2, 6], [3, 1, 2]]

๐Ÿ‘ Example1

Output: 0
Explanation : Cycle 1 โ†’ 0 โ†’ 3 โ†’ 1 has total weight 6 + 4 + 2 = 12, which is positive, so no negative weight cycle exists.

Input : V = 4, edges[][] = [[1, 0, 4], [3, 1, -2], [1, 2, -6], [2, 3, 5]]
๐Ÿ‘ Example2
Output: 1
Explanation : There is a cycle 1 โ†’ 2 โ†’ 3 โ†’ 1 with total weight -3, which is negative, so a negative weight cycle exists.

Detecting Negative Weight Cycle using Bellman-Ford โ€“ O(V * E) Time and O(V) Space

The idea is to use the Bellman-Ford Algorithm where we relax all edges V-1 times to compute shortest paths. In a normal graph, distances stabilize after these iterations. If we can still relax any edge after that, it means the distance is continuously decreasing, which happens only when there is a negative weight cycle in the graph.

  • Initialize a distance array dist with all values as 0
  • Perform edge relaxation (n - 1) times:
    • For each edge (u, v, wt)
    • If dist[u] + wt < dist[v], update dist[v]
  • Run one more iteration over all edges:
    • If any edge still relaxes โ†’ return 1 (negative cycle exists)
  • If no relaxation happens โ†’ return 0

Output
true

Related articles:

Comment
Article Tags: