Detect Negative cycle in a graph

Pattern: Shortest paths

medium

Run Bellman-Ford with every distance starting at 0 (as if a hidden source joined every vertex), so a negative cycle anywhere shows up. After n - 1 rounds, if any edge still relaxes, there is a negative cycle.

The problem

Return whether a directed weighted graph contains a cycle whose total weight is negative, anywhere in the graph. Vertices are numbered from 0 and each edge is [u, v, weight].

Think first

  • Why start every distance at 0 instead of only the source?
  • When is the cycle detected?
  • Why does a cycle of total 0 not count?

Hints

    Brute force, and why it fails

    Floyd-Warshall and check for a negative diagonal: O(V³).

    The key insight

    Starting all distances at 0 makes every vertex a source at once, so one Bellman-Ford run sees every cycle.

    Dry run

    Edges 0→1 (-1), 1→2 (-2), 2→0 (-3). The cycle's total is -6.

    Step 1 of 3

    The plan

    dist = all 0
    repeat n - 1 times: relax all edges
    return any edge still relaxes
    

    Complexity

    Time
    O(V × E)
    Space
    O(V)

    Bellman-Ford rounds.

    Edge cases

    • No edges: false.
    • A self-loop with negative weight: true.
    • A negative edge but no cycle: false.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isNegativeWeightCycle(int n, int[][] edges) {
            long[] dist = new long[n];              // start every vertex at 0: a cycle anywhere will show
            for (int round = 0; round < n - 1; round++)
                for (int[] e : edges) if (dist[e[0]] + e[2] < dist[e[1]]) dist[e[1]] = dist[e[0]] + e[2];
            for (int[] e : edges) if (dist[e[0]] + e[2] < dist[e[1]]) return true;   // still improving: a negative cycle
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool isNegativeWeightCycle(int n, vector<vector<int>>& edges) {
            vector<long long> dist(n, 0);           // start every vertex at 0: a cycle anywhere will show
            for (int round = 0; round < n - 1; round++)
                for (const vector<int>& e : edges) if (dist[e[0]] + e[2] < dist[e[1]]) dist[e[1]] = dist[e[0]] + e[2];
            for (const vector<int>& e : edges) if (dist[e[0]] + e[2] < dist[e[1]]) return true;   // still improving
            return false;
        }
    };

    Python

    class Solution:
        def isNegativeWeightCycle(self, n: int, edges: list[list[int]]) -> bool:
            dist = [0] * n                          # start every vertex at 0: a cycle anywhere will show
            for _ in range(n - 1):
                for u, v, w in edges:
                    if dist[u] + w < dist[v]:
                        dist[v] = dist[u] + w
            return any(dist[u] + w < dist[v] for u, v, w in edges)   # still improving: a negative cycle

    Common mistakes

    • Starting from one source only.
    • Treating a negative edge as a negative cycle.

    Similar problems