Negative Loop Reachable From a Source Vertex
Trees & GraphsAuto-graded · 19 test casesLast updated
Decide whether a weighted directed graph has a negative-total cycle reachable from a given source vertex, using Bellman-Ford while ignoring unreachable regions.
You are given a directed graph with n vertices numbered 0 to n - 1. The graph is described by a list edges, where each entry [u, v, w] is a directed edge from u to v with integer weight w. You are also given a vertex source.
A negative loop is a closed walk that starts and ends at the same vertex along directed edges and whose weights add up to a value strictly less than zero. A self-loop [v, v, w] with w < 0 counts as a negative loop.
Return True if there is a negative loop that can be reached from source, and False otherwise.
A loop is reachable if source can get to at least one vertex on it by following directed edges. source can reach itself with no edges.
Rules:
- Negative loops in parts of the graph that
sourcecannot reach must be ignored. - A loop with total weight exactly
0is not negative. - Parallel edges (same
uandv) are allowed and are treated as separate edges. - Self-loops are allowed.
- If
edgesis empty, the answer isFalse.
Return a boolean.
Constraints
1 <= n <= 10000 <= len(edges) <= 50000 <= u, v < nand0 <= source < n-1000 <= w <= 1000- The graph may contain self-loops and parallel edges.
Examples
Example 1
Input: can_reach_negative_loop(3, [[0, 1, 1], [1, 2, -5], [2, 1, 2]], 0)
Output: True
Example 2
Input: can_reach_negative_loop(3, [[0, 1, 5], [1, 2, -10], [2, 0, 5]], 2)
Output: False
Example 3
Input: can_reach_negative_loop(3, [[0, 1, 5], [1, 2, -20], [2, 0, 5]], 2)
Output: True
Hints
Hint 1
Think about single-source shortest paths when negative weights are allowed. Which classic algorithm handles them and tells you when distances can never settle?
Hint 2
A shortest simple path uses at most n - 1 edges, so n - 1 rounds of relaxing every edge suffice if no negative loop is reachable. What does it mean if one more round can still improve something?
Hint 3
Start every distance at infinity except the source, and only relax an edge when its start vertex already has a finite distance. This keeps loops in unreachable regions from triggering a false positive.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is Bellman-Ford restricted to the part of the graph reachable from source.
- Set every distance to infinity, except
dist[source] = 0. - Repeat up to
n - 1times: go through all edges[u, v, w]and, ifdist[u]is finite anddist[u] + w < dist[v], lowerdist[v]. If a whole round changes nothing, returnFalseimmediately. - Do one more round over all edges. If any edge can still lower a distance, return
True. Otherwise returnFalse.
The check that dist[u] is finite is what restricts the search to the reachable region. Vertices that source cannot reach stay at infinity and never act as relaxation sources, so negative loops there cannot cause a false positive.
Why it is correct
No reachable negative loop. Every reachable vertex has a true shortest distance, achieved by a simple path with at most n - 1 edges. After round k, each distance is at most the best distance using at most k edges. So after n - 1 rounds all reachable distances are final, and the extra round finds nothing to improve. The early exit is also safe, because once a full round changes nothing, no later round can change anything.
A reachable negative loop exists. Let the loop be v0 → v1 → … → vk = v0 with total weight W < 0. All its vertices are reachable, so their distances are finite. Suppose no edge on the loop could be relaxed, so dist[v(i+1)] <= dist[v(i)] + w_i for every loop edge. Summing around the loop cancels the distance terms and gives 0 <= W, a contradiction. So some loop edge can always be relaxed, which means the extra round detects it and a "no change" round can never occur.
Edge cases.
- A negative self-loop
[v, v, w]on a reachable vertex givesdist[v] + w < dist[v], so it is detected. Forn = 1the main loop runs zero times and the extra round catches it. - A zero-weight loop never gives a strict improvement, so it is correctly ignored.
- Parallel edges are each relaxed independently.
- With no edges, nothing changes and the answer is
False.
Complexity
- Time:
O(n * E)in the worst case, about 5 million relaxations at the limits. Early exit often makes it much faster. - Space:
O(n)for the distance array.
Reference solution
from typing import List
def can_reach_negative_loop(n: int, edges: List[List[int]], source: int) -> bool:
INF = float('inf')
dist = [INF] * n
dist[source] = 0
# Up to n - 1 rounds of relaxation.
for _ in range(n - 1):
updated = False
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
updated = True
if not updated:
# Distances are stable, so no reachable negative loop exists.
return False
# One more round: any improvement means a reachable negative loop.
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
return True
return False