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_nodeif there is a directed path (including the zero-edge path atstart_nodeitself) fromstart_nodeto 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 <= 10000 <= len(edges) <= 50000 <= start_node < n0 <= u, v < nfor every[u, v, weight]inedges-1000 <= weight <= 1000
Step-by-step walkthrough
Understand reachability and what counts as a negative cycle
We are given a directed graph (where edges are one-way arrows
u -> vwith integerweight, possibly negative) onnvertices (0ton - 1) and a starting vertexstart_node. We must returnTrueif and only if we can walk along directed edges starting atstart_nodeand reach a cycle whose edge weights add up to strictly less than0.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 ofstart_node—is not reachable fromstart_nodeand must be ignored. - Strictly negative (< 0), not zero (== 0): In Example 2, the cycle1 -> 2 -> 0 -> 1has total weight-7 + 4 + 3 = 0, which is not negative, so the answer isFalse.Why brute-force cycle search fails at n = 1000
A direct brute-force approach finds all vertices reachable from
start_nodeand 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 below0.That works on tiny 5-vertex test cases, where we use it as a cross-check. However, a graph with
n = 1000vertices andm = 5000edges can contain exponentially many simple cycles, so enumerating them will time out. All-pairs Floyd-Warshall (O(n³)) would also take roughly1000³ = 10⁹operations. Instead, we need anO(n * m)single-source algorithm:1000 * 5000 = 5 * 10⁶operations, which finishes in milliseconds.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 fromstart_nodetov(dist[start_node] = 0, andINFeverywhere else). In each pass, we perform edge relaxation across every edge(u, v, weight): if we have already reacheduand walkingu -> vbeats our best cost tov(dist[u] + weight < dist[v]), we lowerdist[v].Why does running
n - 1passes plus one extran-th pass detect reachable negative cycles?- If NO reachable negative cycle exists,
n - 1passes finish the job: Going around a>= 0cycle never makes a walk cheaper, so every shortest path fromstart_nodeis a simple path (no repeated vertices). Onnvertices, a simple path has at mostn - 1edges. Pass1finds all 1-edge shortest paths, Pass2extends them to 2-edge shortest paths, and by Passn - 1every reachable vertex has its final shortest distance—so Passncannot lower anything! - If a reachable negative cycle DOES exist, distances can NEVER stop dropping: Suppose
1 -> 2has weight-5and2 -> 1has weight+2(cycle sum-3 < 0), and both1and2are 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
distand leavesnegative_sum >= 0, a contradiction! Thus at least one edge on the cycle (or downstream of it) must keep decreasing on Passn.- If NO reachable negative cycle exists,
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] * nwith onlydist[start_node] = 0.0and explicitly writingif dist[u] == INF: continue, only vertices genuinely reachable fromstart_nodeever get finite distances or relax their outgoing edges.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 returnTrueif at least onedist[v]decreased. Notice how naturally edge cases fall out: - Self-loops(v, v, w):dist[v] + w < dist[v]isTruewhenw < 0andFalsewhenw >= 0—no special case needed! - Parallel edges: every edge betweenuandvis 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 returnFalse. -n = 1:range(n - 1)isrange(0)(zero regular passes), and the single extra pass checks whether node0has 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)Trace Examples 1, 2, and 3 pass by pass
Let's trace
distacross 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!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 mostnpasses (n - 1settling passes plus 1 detection pass), and each pass scans allmedges once inO(1)per edge—at most1000 * 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 singledistlist of lengthn.
Edge cases
- Disconnected negative cycle (Example 3): Vertices in components unreachable from
start_nodekeepdist == INF, andif dist[u] == INF: continueensures their edges never relax. - Negative cycle that only points into
start_node: Because edges are directed, a cycle with an arrow intostart_node(and no arrow back fromstart_node) still hasdist == INFon 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. Whenn = 1,range(n - 1)performs0settling passes and the single extra pass checks0 + weight < 0, returningTrueforweight = -1andFalseforweight >= 0oredges = []. - Parallel edges: Parallel edges are multiple edges between the same ordered pair
(u, v)with different weights; relaxing every edge inedgesnaturally lets the smallest weight win regardless of list order. - Zero-weight cycles (Example 2): A cycle summing to
0satisfiesdist[u] + weight == dist[v]; strict<prevents it from triggering a false positive. - Negative edges without cycles (DAG): Even steep negative edges like
-1000settle completely withinn - 1passes when they form no cycle, returningFalse.
Common mistakes
- Initializing
dist = [0] * ninstead of[INF] * nwithdist[start_node] = 0: Starting all distances at0detects whether any negative cycle exists anywhere in the graph, failing whenever a negative cycle is unreachable fromstart_node. - Using a finite sentinel like
10**9withoutif dist[u] == BIG: continue: On an unreachable edge(u, v, -5),10**9 + (-5) < 10**9evaluates toTrue, 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 passn. - Running
n - 2settling passes instead ofn - 1: A simple chain ofnvertices (0 -> 1 -> ... -> n - 1) listed in reverse edge order genuinely needs alln - 1passes to propagate from0ton - 1; stopping one pass early makes passn - 1look like a cycle!
Alternative approaches
- BFS/DFS reachability filter + standard Bellman-Ford: First run Breadth-First Search from
start_nodeto collect the setreachableof reachable vertices, discard all edges withu not in reachable, and then run Bellman-Ford on the filtered graph. This has the sameO(n * m)time andO(n + m)space, though keepingINFin 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 vertexvwithdist[start_node][v] < INFends up withdist[v][v] < 0. Easy to code forn <= 200, but too slow (10⁹steps) whenn = 1000.
Follow-up questions
- How can you reconstruct the exact sequence of vertices forming a reachable negative cycle? Record
parent[v] = uwhenever arcu -> vlowersdist[v], and save a vertexxwhose distance drops on then-th pass. Becausexmay sit downstream of the cycle rather than directly on it, walk backwardx = parent[x]ntimes first—by the pigeonhole principle (visitingn + 1vertices amongntotal forces a repeat),xnow lies on the negative cycle. Followparentpointers fromxuntilxreappears, then reverse that list to recover the cycle in forward edge order inO(n * m)time andO(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 andO(n)auxiliary memory. SPFA (Shortest Path Faster Algorithm) keeps a FIFO queue of vertices whosedistrecently improved (seeded withstart_node) and relaxes only outgoing arcs of queued vertices while trackinghop_count[v] = hop_count[u] + 1; reachinghop_count[v] >= nproves a reachable negative cycle exists. Building an adjacency list usesO(n + m)space and typically finishes nearO(m)on sparse inputs, though dense or adversarial inputs still hit theO(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>= 0from a walk never increases its cost, so finite shortest paths still need at mostn - 1edges, distances stabilize by passn - 1, and passnreturnsFalse.
Follow-up questions
- How can you reconstruct the exact sequence of vertices forming a reachable negative cycle?
- How does queue-based Bellman-Ford (SPFA) change the runtime and memory profile compared to fixed-pass relaxation?
- Why do zero-cost loops and positive-weight cycles leave the detection result unaffected?
Similar questions
- Rainwater Collected Across Column Heights
- Streaming Integer Median Queries
- Cycle-Safe Edge Addition in a DAG
- Low-Latency Multi-Tenant Text Classification Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger