Negative Weights: Bellman–Ford, Johnson & Beyond
Negative cycles, reweighting, and the 2022 near-linear-time breakthrough.
Negative edges model refunds, rewards and exchange-rate gains. For real weights, Bellman–Ford's from the 1950s stayed the best bound until 2024; for integer weights, scaling algorithms got below it, and in 2022 a new recursive method reached near-linear time. Along the way: certificates for negative cycles, and the reweighting trick that lets Dijkstra's algorithm run on graphs with negative edges.
What you’ll learn
- Prove Bellman–Ford correct by induction on the number of edges, prove the negative-cycle test, and extract a negative cycle from the parent pointers.
- Prove that reweighting by a potential preserves shortest paths, and derive Johnson's all-pairs algorithm.
- Model arbitrage and systems of difference constraints as negative-cycle and shortest-path problems.
- Describe the scaling algorithms, the near-linear-time algorithm of Bernstein, Nanongkai and Wulff-Nilsen (2022) and its successors, and the recent progress for real weights.
Bellman–Ford, proved
Bellman–Ford relaxes every edge, in any fixed order, once per round. Write for the smallest weight of a path from to with at most edges ( if there is none).
Lower bound. Every finite is the length of some walk from to . With no negative cycle reachable, removing the cycles of a walk never makes it longer, so
Upper bound, by induction on . For , . Let the best path with at most edges end with the edge . After round , , and estimates only decrease, so when round relaxes , whatever the order within the round,
rounds suffice. Without negative cycles, some shortest walk is a simple path, so it has at most edges:
def find_negative_cycle(n, edges):
"""Bellman-Ford from a virtual source (every d = 0). Returns a negative cycle, or None."""
dist, parent = [0] * n, [-1] * n
x = -1
for _ in range(n): # n rounds: a change in round n proves a cycle
x = -1
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v], parent[v], x = dist[u] + w, u, v
if x == -1:
return None # converged: no negative cycle anywhere
for _ in range(n): # walk back n steps to land inside the cycle
x = parent[x]
cycle, v = [x], parent[x]
while v != x:
cycle.append(v)
v = parent[v]
return cycle[::-1]. Starting every estimate at 0 is the same as adding a virtual source with a 0-weight edge to every vertex, so this finds a negative cycle anywhere in the graph. The vertex changed in round may lie after a cycle rather than on it; walking back parent pointers lands inside a cycle of the parent graph, and every such cycle has negative weight.
Constant factors can be shaved: Yen (1970) relaxes the edges in two sweeps over a fixed vertex order, so that about half as many rounds suffice, and Bannister and Eppstein (2012) showed that a random vertex order saves another constant factor in expectation. The worst case remains.
Potentials and Johnson’s algorithm
For a path , the potentials telescope:
Every path between the same two endpoints shifts by the same constant, so the shortest paths are the same paths, and every cycle keeps its weight:
A feasible potential exists if and only if there is no negative cycle. If there is none, add a vertex with 0-weight edges to all vertices and take ; the triangle inequality makes every reduced weight non-negative. Conversely, a feasible gives every cycle .
Johnson's algorithm (1977) turns this into all-pairs shortest paths: one Bellman–Ford run from computes in ; then Dijkstra's algorithm runs from every vertex on the non-negative weights ; finally . With Fibonacci heaps the total is , far below Floyd–Warshall's on sparse graphs: for and , about steps against .
import heapq, math
def johnson(n, edges):
"""All-pairs distances with negative edges allowed; raises ValueError on a negative cycle."""
h = [0] * n # Bellman-Ford from a virtual source q
for _ in range(n):
changed = False
for u, v, w in edges:
if h[u] + w < h[v]:
h[v], changed = h[u] + w, True
if not changed:
break
else:
raise ValueError('negative cycle')
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w + h[u] - h[v])) # reduced weight, never negative
D = []
for s in range(n): # Dijkstra from every vertex
dist, pq = [math.inf] * n, [(0, s)]
dist[s] = 0
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(pq, (dist[v], v))
D.append([dist[v] - h[s] + h[v] for v in range(n)]) # undo the shift
return DWith binary heaps this is . The same potential trick turns A* with a consistent heuristic into Dijkstra's algorithm on reduced weights.
Why not remove negative weights more simply, by adding the same constant to every edge?
- It works whenever is at least the largest negative weight's magnitude
- It fails only when the graph has a negative cycle
- A path with more edges gains more, so the shortest path can change
- It works for Dijkstra's algorithm but not for Bellman–Ford
Show the answer
C. A path with more edges gains more, so the shortest path can change
A path with edges gains , so paths are no longer shifted equally. With of weight and with two edges of , the shortest path is (); after adding 2 to every edge, costs 1 and costs 2, so the wrong path wins. Potentials shift every path between two vertices by the same amount, which is why they work.
Negative cycles in disguise
Arbitrage. Make each currency a vertex, and let be the units of that one unit of buys. Going around a cycle multiplies your money by the product of its rates, which is a profit when the product exceeds 1. Logarithms turn products into sums, so with a profitable cycle is exactly a negative cycle, and find_negative_cycle locates one in :
One US dollar buys 0.9 euros, one euro buys 0.9 pounds, and one pound buys 1.25 dollars. How many dollars do 1,000 dollars become after one trip around dollars, euros, pounds and back?
Show the answer
1012.5
, a gain of 1.25%. The cycle's weight is . If the reverse trades pay 1.1 dollars per euro, 1.1 euros per pound and 0.79 pounds per dollar, every other cycle loses money (products 0.99, 0.99, 0.9875 and about 0.956), and Bellman–Ford finds exactly this one.
Difference constraints. A system of constraints is a shortest-path problem in disguise. They arise in scheduling with time windows: "task starts at most after task " is , and "at least after" is . Build the constraint graph: an edge of weight for every constraint, plus a source with a 0-weight edge to every variable.
Beyond O(nm)
For real weights, nothing asymptotically better than was known for decades. For integer weights at least , scaling helped: process the bits of the weights from the most significant down; at each scale the potential from the previous scale almost works, and repairing it is a problem with tiny negative weights. Gabow and Tarjan (1989) and Goldberg (1995) reached this way.
How it works, in outline.
- Scaling reduces the problem to instances whose weights are at least , each asking for a feasible potential; one run of Dijkstra's algorithm on the reduced weights then finishes.
- In the graph with every negative weight raised to 0, a low-diameter decomposition deletes a few edges at random, so that every remaining strongly connected piece has small diameter, each edge being deleted with probability proportional to its weight.
- Potentials are fixed recursively inside the pieces; the pieces form a DAG, handled by relaxation in topological order; and the remaining negative edges are absorbed by a hybrid of Dijkstra's algorithm and Bellman–Ford whose running time grows with the number of negative edges on shortest paths, which the decomposition keeps small in expectation.
Real weights. Fineman (STOC 2024) gave the first algorithm asymptotically faster than for real weights: randomized, with running time . It eliminates negative edges a randomly sampled batch at a time, computing potentials that make each batch non-negative. Huang, Jin and Quanrud (SODA 2025) improved the bound to , and the line of work continues.
| Year | Result | Weights | Time |
|---|---|---|---|
| 1950s | Bellman–Ford–Moore | real | |
| 1977 | Johnson's reweighting, all pairs | real | |
| 1989–1995 | Gabow–Tarjan, Goldberg (scaling) | integers | |
| 2022 | Bernstein, Nanongkai & Wulff-Nilsen | integers | , randomized |
| 2023 | Bringmann, Cassis & Fischer | integers | , randomized |
| 2024 | Fineman | real | , randomized |
| 2025 | Huang, Jin & Quanrud | real | , randomized |
Key takeaways
- After round , Bellman–Ford's estimates are at most the best paths with edges, so rounds suffice without negative cycles; an edge that still relaxes proves one, and walking parent pointers back finds it.
- A potential shifts every – path by and leaves cycles unchanged; distances from a virtual source form a feasible potential, which gives Johnson's all-pairs algorithm.
- Arbitrage is a negative cycle under weights , and difference constraints are feasible exactly when their graph has no negative cycle, with as a solution.
- Integer weights: scaling reached (1989–1995), then near-linear time (Bernstein, Nanongkai & Wulff-Nilsen, FOCS 2022; Bringmann, Cassis & Fischer, FOCS 2023). Real weights: stood until Fineman's (STOC 2024).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Within each round, Bellman–Ford may relax the edges in any order. Why does the order not affect correctness?
- Because estimates only decrease, the bound after round holds for every order; the order only changes how quickly the estimates converge
- Because every order relaxes the edges of a shortest path in path order
- It does affect correctness: the edges must be sorted by weight
- Because Bellman–Ford recomputes all estimates from scratch in each round
Show the answer
A. Because estimates only decrease, the bound after round holds for every order; the order only changes how quickly the estimates converge
The induction only needs when the edge is relaxed in round , which holds whatever happened earlier in the round. A lucky order can finish a path in a single round, which is what Yen's ordering exploits.
In round , Bellman–Ford still lowers the estimate of a vertex . Why walk back parent pointers from before reading off the cycle?
- To compute the weight of the cycle
- Because may lie after the cycle rather than on it, and steps back are sure to land inside a cycle of the parent graph
- Because parent pointers are stored in reverse order
- To keep the total running time within
Show the answer
B. Because may lie after the cycle rather than on it, and steps back are sure to land inside a cycle of the parent graph
The change at can be a ripple from a negative cycle upstream. Following parent pointers from any vertex either reaches the source or enters a cycle, and here it cannot reach the source in steps, so after steps it is inside a cycle; cycles in the parent graph always have negative weight.
All pairs on a sparse graph with vertices, edges and some negative weights, but no negative cycle. How do Johnson's algorithm and Floyd–Warshall compare?
- They are the same: both are
- Floyd–Warshall is faster, because Johnson's algorithm runs Dijkstra's algorithm times
- Johnson's algorithm cannot be used, because of the negative weights
- Johnson's algorithm is faster by orders of magnitude: about steps against
Show the answer
D. Johnson's algorithm is faster by orders of magnitude: about steps against
for Johnson's algorithm, against for Floyd–Warshall. On dense graphs, with , the two meet at .
A system of constraints has the constraint graph with an edge of weight per constraint, plus a source with 0-weight edges to every variable. Bellman–Ford from finds no negative cycle. Which assignment satisfies every constraint?
- for every
- = the number of edges on a shortest path from to
Show the answer
A.
The triangle inequality is exactly the constraint . Adding the same constant to every gives more solutions; if Bellman–Ford had found a negative cycle, summing its constraints would give a negative number, so no solution would exist.
Further reading
- D. B. Johnson, "Efficient algorithms for shortest paths in sparse networks," Journal of the ACM 24(1) (1977), 1–13.
- A. V. Goldberg, "Scaling algorithms for the shortest paths problem," SIAM Journal on Computing 24(3) (1995), 494–504.
- A. Bernstein, D. Nanongkai & C. Wulff-Nilsen, "Negative-Weight Single-Source Shortest Paths in Near-linear Time," FOCS (2022).
- K. Bringmann, A. Cassis & N. Fischer, "Negative-Weight Single-Source Shortest Paths in Near-Linear Time: Now Faster!," FOCS (2023).
- J. T. Fineman, "Single-Source Shortest Paths with Negative Real Weights in Time," STOC (2024).