Skip to problem
←

Detect a Negative-Weight Cycle

Medium 0 attempts

You're given a weighted, directed graph with V vertices and a list of edges. Determine whether it contains a negative-weight cycle — a cycle whose edge weights sum to less than zero — using the Bellman-Ford shortest-path algorithm.

Check the entire graph, including components that cannot be reached from vertex 0. A zero-weight cycle is not negative.

Function contract

Implement hasNegativeCycle(V, edges), where each directed edge is [from, to, weight] and vertices are numbered 0 through V - 1.

Output: true if any connected component contains a directed cycle with negative total weight; otherwise false.

Example 1

Input
V = 4
edges = [[0,1,-1],[1,2,-2],[2,3,-3],[3,0,4]]
Output
true

Explanation: The cycle 0 → 1 → 2 → 3 → 0 has weight -1 - 2 - 3 + 4 = -2.

Example 2

Input
V = 4
edges = [[2,3,-1],[3,2,-1]]
Output
true

Example 3

Input
V = 3
edges = [[0,1,-1],[1,2,2]]
Output
false
Constraints
  • 1 <= V <= 100
  • 0 <= edges.length <= V * (V - 1)
  • -1000 <= weight <= 1000
  • Edge endpoints are valid vertex indices; there are no self-loops or repeated ordered edges.
Topics

Bellman-Ford

Initialize every distance to zero, equivalent to adding a virtual source with zero-weight edges to all vertices. This includes disconnected components. Run V - 1 relaxation passes, then check whether any edge can still reduce a distance.

javascript
function hasNegativeCycle(V, edges) {
  // A virtual source reaches every component with a zero-weight edge.
  const dist = Array(V).fill(0);
  for (let i = 0; i < V - 1; i++) {
    for (const [u, v, w] of edges) {
      if (dist[u] !== Infinity && dist[u] + w < dist[v]) dist[v] = dist[u] + w;
    }
  }
  for (const [u, v, w] of edges) {
    if (dist[u] !== Infinity && dist[u] + w < dist[v]) return true;
  }
  return false;
}

Time: O(V + V × E), including initialization | Space: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript