Reachable Negative-Weight Cycle Detection

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given a weighted directed graph with n vertices numbered 0 through n - 1, a list of directed edges edges where each entry [u, v, weight] represents a one-way arc from vertex u to vertex v with integer cost weight, and an origin vertex start_node.

Determine whether there exists at least one negative-weight cycle that can be reached along directed edges starting from start_node.

  • A negative-weight cycle is a non-empty closed walk of directed edges returning to its starting vertex whose edge weights add up to strictly less than 0.
  • A cycle is reachable from start_node if there is a directed path (including the zero-edge path at start_node itself) from start_node to any vertex belonging to that cycle.
  • The graph may include self-loops (u == v) and multiple parallel edges between the same ordered pair (u, v).
def has_reachable_negative_cycle(
    n: int,
    edges: List[List[int]],
    start_node: int,
) -> bool:

Return True if a reachable negative-weight cycle exists, or False otherwise.

Examples

Example 1

Input:
  n = 4
  edges = [[0, 1, 4], [1, 2, -6], [2, 3, 1], [3, 1, 2]]
  start_node = 0
Output:
  True

Walk-through: Edge 0 -> 1 reaches vertex 1, which lies on the directed loop 1 -> 2 -> 3 -> 1 with total cost -6 + 1 + 2 = -3 < 0. Because a negative-weight cycle is reachable from 0, the answer is True.

Example 2

Input:
  n = 3
  edges = [[0, 1, 3], [1, 2, -7], [2, 0, 4]]
  start_node = 1
Output:
  False

Walk-through: Starting from vertex 1, the only cycle 1 -> 2 -> 0 -> 1 has net cost -7 + 4 + 3 = 0. Since 0 is not strictly less than 0, no negative-weight cycle exists, and the answer is False.

Example 3

Input:
  n = 4
  edges = [[0, 1, 2], [2, 3, -8], [3, 2, 3]]
  start_node = 0
Output:
  False

Walk-through: Vertices 2 and 3 form a negative-weight cycle (-8 + 3 = -5 < 0), but start_node = 0 can only reach {0, 1}. Because the negative cycle is unreachable from 0, the answer is False.

Constraints

  • 1 <= n <= 1000
  • 0 <= len(edges) <= 5000
  • 0 <= start_node < n
  • 0 <= u, v < n for every [u, v, weight] in edges
  • -1000 <= weight <= 1000

Step-by-step walkthrough

  1. Understand reachability and what counts as a negative cycle

    We are given a directed graph (where edges are one-way arrows u -> v with integer weight, possibly negative) on n vertices (0 to n - 1) and a starting vertex start_node. We must return True if and only if we can walk along directed edges starting at start_node and reach a cycle whose edge weights add up to strictly less than 0.

    Reachable vs. unreachable cycles when start_node = 0:
    
      [5] <==(-4)==> [6]          [0] ---(+4)---> [1] ---(-6)---> [2]          [3] <==(-8)==> [4]
        \            (cycle -3,     ^               ^               |            (cycle -5, in a
         \---(+3)---> but arrows    |               \---(+2)--[3]<--/             disconnected
                      only enter 0!)               (cycle -3, REACHABLE           component -> ignore!)
                                                    from 0 -> returns True!)
    

    Keep two boundary rules crystal clear: - Direction of reachability matters: A cycle in a disconnected component (Example 3)—or a cycle that has a one-way path into start_node (5 <-> 6 -> 0) with no path out of start_node—is not reachable from start_node and must be ignored. - Strictly negative (< 0), not zero (== 0): In Example 2, the cycle 1 -> 2 -> 0 -> 1 has total weight -7 + 4 + 3 = 0, which is not negative, so the answer is False.

  2. Why brute-force cycle search fails at n = 1000

    A direct brute-force approach finds all vertices reachable from start_node and uses backtracking to enumerate every simple cycle (a closed loop that visits no vertex twice except returning to its start), checking whether any loop sums below 0.

    That works on tiny 5-vertex test cases, where we use it as a cross-check. However, a graph with n = 1000 vertices and m = 5000 edges can contain exponentially many simple cycles, so enumerating them will time out. All-pairs Floyd-Warshall (O(n³)) would also take roughly 1000³ = 10⁹ operations. Instead, we need an O(n * m) single-source algorithm: 1000 * 5000 = 5 * 10⁶ operations, which finishes in milliseconds.

  3. Key idea: Bellman-Ford settles in n - 1 passes unless a negative cycle exists

    The Bellman-Ford algorithm tracks an array dist[v] holding the cheapest walk cost found so far from start_node to v (dist[start_node] = 0, and INF everywhere else). In each pass, we perform edge relaxation across every edge (u, v, weight): if we have already reached u and walking u -> v beats our best cost to v (dist[u] + weight < dist[v]), we lower dist[v].

    Why does running n - 1 passes plus one extra n-th pass detect reachable negative cycles?

    1. If NO reachable negative cycle exists, n - 1 passes finish the job: Going around a >= 0 cycle never makes a walk cheaper, so every shortest path from start_node is a simple path (no repeated vertices). On n vertices, a simple path has at most n - 1 edges. Pass 1 finds all 1-edge shortest paths, Pass 2 extends them to 2-edge shortest paths, and by Pass n - 1 every reachable vertex has its final shortest distance—so Pass n cannot lower anything!
    2. If a reachable negative cycle DOES exist, distances can NEVER stop dropping: Suppose 1 -> 2 has weight -5 and 2 -> 1 has weight +2 (cycle sum -3 < 0), and both 1 and 2 are reachable (dist < INF). Could a pass ever leave both edges unrelaxed? If neither edge lowered its target, both inequalities below would have to hold at the same time:
      No change on 1 -> 2 (-5):    dist[1] + (-5) >= dist[2]
      No change on 2 -> 1 (+2):    dist[2] + (+2) >= dist[1]
      --------------------------------------------------------
      Add both sides together:     dist[1] + dist[2] - 3 >= dist[2] + dist[1]
      Cancel dist[1] + dist[2]:                       -3 >= 0   (Impossible!)
    

    Around any cycle with negative total weight, adding up "no edge improved" cancels every vertex's dist and leaves negative_sum >= 0, a contradiction! Thus at least one edge on the cycle (or downstream of it) must keep decreasing on Pass n.

  4. Guard against unreachable negative cycles with INF

    There is one trap that breaks many Bellman-Ford implementations: how you handle unreached vertices (dist[u] == INF).

    Trap if you use BIG = 10**9 without skipping dist[u] == BIG:
      Suppose start_node = 0 has NO edges, while 2 -> 3 (-5) and 3 -> 2 (+1) form an unreachable -4 cycle.
      dist starts at [0, BIG, BIG, BIG].
      Checking edge 2 -> 3 (-5):  BIG + (-5) = 999,999,995 < BIG  --> dist[3] drops!
      The unreachable cycle keeps relaxing itself and falsely returns True!
    

    Similarly, initializing dist = [0] * n (a trick used when looking for any negative cycle anywhere in the graph) treats every vertex as already reached from step 0 and falsely reports disconnected cycles.

    By initializing dist = [INF] * n with only dist[start_node] = 0.0 and explicitly writing if dist[u] == INF: continue, only vertices genuinely reachable from start_node ever get finite distances or relax their outgoing edges.

  5. Code one relaxation pass and the n-pass Bellman-Ford check

    Let's write relax_all_edges(dist, edges) to run a single pass and return True if at least one dist[v] decreased. Notice how naturally edge cases fall out: - Self-loops (v, v, w): dist[v] + w < dist[v] is True when w < 0 and False when w >= 0—no special case needed! - Parallel edges: every edge between u and v is checked independently, so the cheapest edge wins automatically. - Early exit: if any pass changes nothing (not relax_all_edges(...)), no later pass can ever change anything either, so we immediately return False. - n = 1: range(n - 1) is range(0) (zero regular passes), and the single extra pass checks whether node 0 has a negative self-loop!

    INF = float("inf")
    
    
    def relax_all_edges(dist: List[float], edges: List[List[int]]) -> bool:
        """Run one Bellman-Ford pass over all edges; return True if any distance decreased."""
        any_updated = False
        for u, v, weight in edges:
            # Skip unreached sources so negative cycles in unreachable components never trigger.
            if dist[u] == INF:
                continue
    
            candidate_dist = dist[u] + weight
            # Strict '<' ensures zero-weight cycles (candidate_dist == dist[v]) do not count as negative.
            if candidate_dist < dist[v]:
                dist[v] = candidate_dist
                any_updated = True
        return any_updated
    
    
    def has_reachable_negative_cycle(n: int, edges: List[List[int]], start_node: int) -> bool:
        # dist: length-n list where dist[v] is the lowest walk cost found from start_node to v (INF if unreached).
        dist: List[float] = [INF] * n
        dist[start_node] = 0.0
    
        # Phase 1: Without a reachable negative cycle, every shortest path has at most n - 1 edges,
        # so at most n - 1 passes are needed for all reachable distances to settle.
        for _ in range(n - 1):
            if not relax_all_edges(dist, edges):
                # Once a full pass changes nothing, no future pass can change anything either.
                return False
    
        # Phase 2 (n-th pass): Any further decrease proves a reachable negative-weight cycle exists.
        return relax_all_edges(dist, edges)
    
  6. Trace Examples 1, 2, and 3 pass by pass

    Let's trace dist across every pass on the three example graphs:

    Example 1: n = 4, edges = [(0,1,4), (1,2,-6), (2,3,1), (3,1,2)], start_node = 0  (cycle sum -3)
      Initial:              dist = [0, inf, inf, inf]
      Pass 1 (of 3):        0->1: 4; 1->2: -2; 2->3: -1; 3->1: 1 (< 4) -> dist = [0, 1, -2, -1]
      Pass 2 (of 3):        1->2: -5; 2->3: -4; 3->1: -2               -> dist = [0, -2, -5, -4]
      Pass 3 (of 3):        1->2: -8; 2->3: -7; 3->1: -5               -> dist = [0, -5, -8, -7]
      Extra Pass (Pass 4):  1->2 sets dist[2] = -11 < -8 -> updated!   ===> returns True!
    
    Example 2: n = 3, edges = [(0,1,3), (1,2,-7), (2,0,4)], start_node = 1           (cycle sum 0)
      Initial:              dist = [inf, 0, inf]
      Pass 1 (of 2):        0->1 skipped; 1->2 sets dist[2] = -7; 2->0 sets dist[0] = -3
                            dist = [-3, 0, -7]
      Pass 2 (of 2):        -3+3=0, 0-7=-7, -7+4=-3 -> nothing decreases (early exit) ===> returns False!
    
    Example 3: n = 4, edges = [(0,1,2), (2,3,-8), (3,2,3)], start_node = 0           (unreachable -5)
      Initial:              dist = [0, inf, inf, inf]
      Pass 1 (of 3):        0->1 sets dist[1] = 2; 2->3 and 3->2 skipped (dist == inf)
                            dist = [0, 2, inf, inf]
      Pass 2 (of 3):        0->1 gives 2; 2->3 and 3->2 skipped -> early exit         ===> returns False!
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    INF = float("inf")
    
    
    def relax_all_edges(dist: List[float], edges: List[List[int]]) -> bool:
        """Run one Bellman-Ford pass over all edges; return True if any distance decreased."""
        any_updated = False
        for u, v, weight in edges:
            # Skip unreached sources so negative cycles in unreachable components never trigger.
            if dist[u] == INF:
                continue
    
            candidate_dist = dist[u] + weight
            # Strict '<' ensures zero-weight cycles (candidate_dist == dist[v]) do not count as negative.
            if candidate_dist < dist[v]:
                dist[v] = candidate_dist
                any_updated = True
        return any_updated
    
    
    def has_reachable_negative_cycle(n: int, edges: List[List[int]], start_node: int) -> bool:
        # dist: length-n list where dist[v] is the lowest walk cost found from start_node to v (INF if unreached).
        dist: List[float] = [INF] * n
        dist[start_node] = 0.0
    
        # Phase 1: Without a reachable negative cycle, every shortest path has at most n - 1 edges,
        # so at most n - 1 passes are needed for all reachable distances to settle.
        for _ in range(n - 1):
            if not relax_all_edges(dist, edges):
                # Once a full pass changes nothing, no future pass can change anything either.
                return False
    
        # Phase 2 (n-th pass): Any further decrease proves a reachable negative-weight cycle exists.
        return relax_all_edges(dist, edges)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a flight network between n cities where most flights cost money (positive weight) and a few promotional routes pay you a cash rebate (negative weight). A negative-weight cycle is a round-trip loop of flights that leaves you with more money than you started with—meaning if you can fly to that loop starting from your home airport (start_node), you could circle it forever and drive your net travel cost down without limit.

Why do simpler approaches fail? Enumerating cycles with Depth-First Search (DFS) blows up exponentially because a 1,000-node graph can contain billions of distinct loops. Meanwhile, Dijkstra's algorithm breaks on negative weights, and running Bellman-Ford with all starting distances set to 0 falsely triggers on profitable loops sitting in disconnected islands you can never fly to from start_node.

Instead, we run the Bellman-Ford algorithm (which repeatedly checks every edge u -> v to see if dist[u] + weight < dist[v], an update called edge relaxation) starting with dist[start_node] = 0 and INF everywhere else. If no reachable negative loop exists, every cheapest route is a simple path (visiting no city twice) of at most n - 1 flights, so all prices settle within n - 1 passes. If any city's price still drops on pass n, a reachable negative loop must be pumping prices downward!

Example 1: n = 4, start_node = 0, edges = [(0, 1, +4), (1, 2, -6), (2, 3, +1), (3, 1, +2)]
  Loop 1 -> 2 -> 3 -> 1 has net weight -6 + 1 + 2 = -3 (reachable from 0).

  Start:              dist = [0, inf, inf, inf]
  Pass 1 (1st of 3):  0->1: 4; 1->2: -2; 2->3: -1; 3->1: 1   -> dist = [0, 1, -2, -1]
  Pass 2 (2nd of 3):  1->2: -5; 2->3: -4; 3->1: -2           -> dist = [0, -2, -5, -4]
  Pass 3 (3rd of 3):  1->2: -8; 2->3: -7; 3->1: -5           -> dist = [0, -5, -8, -7]
  Pass 4 (n-th pass): 1->2 gives -11 < -8 (still dropping!)  -> returns True

Complexity

Let n be the number of vertices (1 <= n <= 1000) and m be len(edges) (0 <= m <= 5000).

  • Time: O(n * m) in the worst case. We run at most n passes (n - 1 settling passes plus 1 detection pass), and each pass scans all m edges once in O(1) per edge—at most 1000 * 5000 = 5 * 10⁶ edge checks. When no negative cycle is reachable and shortest paths are short, the early-exit check stops as soon as a pass makes zero updates.
  • Space: O(n) auxiliary memory. Aside from the input graph, we allocate a single dist list of length n.

Edge cases

  • Disconnected negative cycle (Example 3): Vertices in components unreachable from start_node keep dist == INF, and if dist[u] == INF: continue ensures their edges never relax.
  • Negative cycle that only points into start_node: Because edges are directed, a cycle with an arrow into start_node (and no arrow back from start_node) still has dist == INF on its vertices and is rightly ignored.
  • Single vertex (n = 1) and self-loops: A self-loop is an edge (v, v, weight) from a vertex to itself. When n = 1, range(n - 1) performs 0 settling passes and the single extra pass checks 0 + weight < 0, returning True for weight = -1 and False for weight >= 0 or edges = [].
  • Parallel edges: Parallel edges are multiple edges between the same ordered pair (u, v) with different weights; relaxing every edge in edges naturally lets the smallest weight win regardless of list order.
  • Zero-weight cycles (Example 2): A cycle summing to 0 satisfies dist[u] + weight == dist[v]; strict < prevents it from triggering a false positive.
  • Negative edges without cycles (DAG): Even steep negative edges like -1000 settle completely within n - 1 passes when they form no cycle, returning False.

Common mistakes

  • Initializing dist = [0] * n instead of [INF] * n with dist[start_node] = 0: Starting all distances at 0 detects whether any negative cycle exists anywhere in the graph, failing whenever a negative cycle is unreachable from start_node.
  • Using a finite sentinel like 10**9 without if dist[u] == BIG: continue: On an unreachable edge (u, v, -5), 10**9 + (-5) < 10**9 evaluates to True, letting unreachable negative cycles lower their own sentinel values and trigger false positives.
  • Using <= instead of < during relaxation: Relaxing on ties (<=) causes zero-weight cycles and zero-weight self-loops to keep updating forever on pass n.
  • Running n - 2 settling passes instead of n - 1: A simple chain of n vertices (0 -> 1 -> ... -> n - 1) listed in reverse edge order genuinely needs all n - 1 passes to propagate from 0 to n - 1; stopping one pass early makes pass n - 1 look like a cycle!

Alternative approaches

  • BFS/DFS reachability filter + standard Bellman-Ford: First run Breadth-First Search from start_node to collect the set reachable of reachable vertices, discard all edges with u not in reachable, and then run Bellman-Ford on the filtered graph. This has the same O(n * m) time and O(n + m) space, though keeping INF in a single Bellman-Ford pass achieves the exact same filtering in half the code.
  • Floyd-Warshall: Compute all-pairs shortest paths in O(n³) time and check whether any vertex v with dist[start_node][v] < INF ends up with dist[v][v] < 0. Easy to code for n <= 200, but too slow (10⁹ steps) when n = 1000.

Follow-up questions

  • How can you reconstruct the exact sequence of vertices forming a reachable negative cycle? Record parent[v] = u whenever arc u -> v lowers dist[v], and save a vertex x whose distance drops on the n-th pass. Because x may sit downstream of the cycle rather than directly on it, walk backward x = parent[x] n times first—by the pigeonhole principle (visiting n + 1 vertices among n total forces a repeat), x now lies on the negative cycle. Follow parent pointers from x until x reappears, then reverse that list to recover the cycle in forward edge order in O(n * m) time and O(n) space.
  • How does queue-based Bellman-Ford (SPFA) change the runtime and memory profile compared to fixed-pass relaxation? Fixed-pass Bellman-Ford runs in O(n * m) worst-case time and O(n) auxiliary memory. SPFA (Shortest Path Faster Algorithm) keeps a FIFO queue of vertices whose dist recently improved (seeded with start_node) and relaxes only outgoing arcs of queued vertices while tracking hop_count[v] = hop_count[u] + 1; reaching hop_count[v] >= n proves a reachable negative cycle exists. Building an adjacency list uses O(n + m) space and typically finishes near O(m) on sparse inputs, though dense or adversarial inputs still hit the O(n * m) worst-case bound.
  • Why do zero-cost loops and positive-weight cycles leave the detection result unaffected? Traversing a positive-weight cycle raises walk cost (dist[u] + weight > dist[v]), while traversing a zero-cost loop leaves walk cost tied (dist[u] + weight == dist[v]), which strict < ignores. Removing any cycle of total weight >= 0 from a walk never increases its cost, so finite shortest paths still need at most n - 1 edges, distances stabilize by pass n - 1, and pass n returns False.

Follow-up questions

Similar questions

More Hive.Ai interview questions

All 5 Hive.Ai questions →