Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 O(nm)O(nm) 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 O(nm+n2log⁡n)O(nm + n^2\log n) 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 δi(s,v)\delta_i(s, v) for the smallest weight of a path from ss to vv with at most ii edges (∞\infty if there is none).

DerivationProof
  1. d[v]≥δ(s,v)d[v] \ge \delta(s, v)

    Lower bound. Every finite d[v]d[v] is the length of some walk from ss to vv. With no negative cycle reachable, removing the cycles of a walk never makes it longer, so

  2. d[v]≤d[u]+w(u,v)≤δi−1(s,u)+w(u,v)=δi(s,v)d[v] \le d[u] + w(u, v) \le \delta_{i-1}(s, u) + w(u, v) = \delta_i(s, v)

    Upper bound, by induction on ii. For i=0i = 0, d[s]=0=δ0(s,s)d[s] = 0 = \delta_0(s, s). Let the best path with at most ii edges end with the edge u→vu \to v. After round i−1i - 1, d[u]≤δi−1(s,u)d[u] \le \delta_{i-1}(s, u), and estimates only decrease, so when round ii relaxes u→vu \to v, whatever the order within the round,

  3. δ(s,v)≤d[v]≤δn−1(s,v)=δ(s,v)\delta(s, v) \le d[v] \le \delta_{n-1}(s, v) = \delta(s, v)

    n−1n - 1 rounds suffice. Without negative cycles, some shortest walk is a simple path, so it has at most n−1n - 1 edges:

python
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]

O(nm)O(nm). 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 xx changed in round nn may lie after a cycle rather than on it; walking back nn 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 O(nm)O(nm) worst case remains.

Potentials and Johnson’s algorithm

DerivationReweighting preserves shortest paths
  1. wh(P)=∑i=1k(w(vi−1,vi)+h(vi−1)−h(vi))=w(P)+h(v0)−h(vk)w_h(P) = \sum_{i=1}^{k}\big(w(v_{i-1}, v_i) + h(v_{i-1}) - h(v_i)\big) = w(P) + h(v_0) - h(v_k)

    For a path P=v0→v1→⋯→vkP = v_0 \to v_1 \to \cdots \to v_k, the potentials telescope:

  2. δh(u,v)=δ(u,v)+h(u)−h(v),wh(C)=w(C)\delta_h(u, v) = \delta(u, v) + h(u) - h(v), \qquad w_h(C) = w(C)

    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:

  3. h(v)≤h(u)+w(u,v)  ⟺  wh(u,v)≥0h(v) \le h(u) + w(u, v) \;\Longleftrightarrow\; w_h(u, v) \ge 0

    A feasible potential exists if and only if there is no negative cycle. If there is none, add a vertex qq with 0-weight edges to all vertices and take h(v)=δ(q,v)h(v) = \delta(q, v); the triangle inequality makes every reduced weight non-negative. Conversely, a feasible hh gives every cycle w(C)=wh(C)≥0w(C) = w_h(C) \ge 0.

Johnson's algorithm (1977) turns this into all-pairs shortest paths: one Bellman–Ford run from qq computes hh in O(nm)O(nm); then Dijkstra's algorithm runs from every vertex on the non-negative weights whw_h; finally δ(u,v)=δh(u,v)−h(u)+h(v)\delta(u, v) = \delta_h(u, v) - h(u) + h(v). With Fibonacci heaps the total is O(nm+n2log⁡n)O(nm + n^2\log n), far below Floyd–Warshall's O(n3)O(n^3) on sparse graphs: for n=104n = 10^4 and m=5×104m = 5 \times 10^4, about 2×1092 \times 10^9 steps against 101210^{12}.

python
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 D

With binary heaps this is O(nmlog⁡n)O(nm\log n). The same potential trick turns A* with a consistent heuristic into Dijkstra's algorithm on reduced weights.

Check your understanding

Why not remove negative weights more simply, by adding the same constant cc to every edge?

  1. It works whenever cc is at least the largest negative weight's magnitude
  2. It fails only when the graph has a negative cycle
  3. A path with more edges gains more, so the shortest path can change
  4. 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 kk edges gains kckc, so paths are no longer shifted equally. With S→TS \to T of weight −1-1 and S→A→TS \to A \to T with two edges of −1-1, the shortest path is S→A→TS \to A \to T (−2-2); after adding 2 to every edge, S→TS \to T costs 1 and S→A→TS \to A \to T 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 r(a,b)r(a, b) be the units of bb that one unit of aa 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 w(a,b)=−ln⁡r(a,b)w(a, b) = -\ln r(a, b) a profitable cycle is exactly a negative cycle, and find_negative_cycle locates one in O(nm)O(nm):

∏ir(ai−1,ai)>1⟺∑i−ln⁡r(ai−1,ai)<0\prod_{i} r(a_{i-1}, a_i) > 1 \quad\Longleftrightarrow\quad \sum_{i} -\ln r(a_{i-1}, a_i) < 0
Predict before you look

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

1000×0.9×0.9×1.25=1012.51000 \times 0.9 \times 0.9 \times 1.25 = 1012.5, a gain of 1.25%. The cycle's weight is −ln⁡1.0125≈−0.0124<0-\ln 1.0125 \approx -0.0124 < 0. 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 xj−xi≤cijx_j - x_i \le c_{ij} is a shortest-path problem in disguise. They arise in scheduling with time windows: "task jj starts at most cc after task ii" is xj−xi≤cx_j - x_i \le c, and "at least dd after" is xi−xj≤−dx_i - x_j \le -d. Build the constraint graph: an edge i→ji \to j of weight cijc_{ij} for every constraint, plus a source qq with a 0-weight edge to every variable.

Beyond O(nm)

For real weights, nothing asymptotically better than O(nm)O(nm) was known for decades. For integer weights at least −W-W, 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 O(mnlog⁡W)O(m\sqrt{n}\log W) this way.

How it works, in outline.

  1. Scaling reduces the problem to O(log⁡W)O(\log W) instances whose weights are at least −1-1, each asking for a feasible potential; one run of Dijkstra's algorithm on the reduced weights then finishes.
  2. 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.
  3. 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 O(nm)O(nm) for real weights: randomized, with running time O~(mn8/9)\tilde O(mn^{8/9}). 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 O~(mn4/5)\tilde O(mn^{4/5}), and the line of work continues.

YearResultWeightsTime
1950sBellman–Ford–MoorerealO(nm)O(nm)
1977Johnson's reweighting, all pairsrealO(nm+n2log⁡n)O(nm + n^2\log n)
1989–1995Gabow–Tarjan, Goldberg (scaling)integers ≥−W\ge -WO(mnlog⁡W)O(m\sqrt{n}\log W)
2022Bernstein, Nanongkai & Wulff-Nilsenintegers ≥−W\ge -WO(mlog⁡8nlog⁡W)O(m\log^8 n\log W), randomized
2023Bringmann, Cassis & Fischerintegers ≥−W\ge -WO(mlog⁡2nlog⁡(nW)log⁡log⁡n)O(m\log^2 n\log(nW)\log\log n), randomized
2024FinemanrealO~(mn8/9)\tilde O(mn^{8/9}), randomized
2025Huang, Jin & QuanrudrealO~(mn4/5)\tilde O(mn^{4/5}), randomized
Single-source bounds except Johnson's row. O~\tilde O hides polylogarithmic factors.

Key takeaways

  • After round ii, Bellman–Ford's estimates are at most the best paths with ii edges, so n−1n - 1 rounds suffice without negative cycles; an edge that still relaxes proves one, and walking nn parent pointers back finds it.
  • A potential hh shifts every uu–vv path by h(u)−h(v)h(u) - h(v) and leaves cycles unchanged; distances from a virtual source form a feasible potential, which gives Johnson's O(nm+n2log⁡n)O(nm + n^2\log n) all-pairs algorithm.
  • Arbitrage is a negative cycle under weights −ln⁡(rate)-\ln(\text{rate}), and difference constraints xj−xi≤cx_j - x_i \le c are feasible exactly when their graph has no negative cycle, with x=δ(q,⋅)x = \delta(q, \cdot) as a solution.
  • Integer weights: scaling reached O(mnlog⁡N)O(m\sqrt{n}\log N) (1989–1995), then near-linear time (Bernstein, Nanongkai & Wulff-Nilsen, FOCS 2022; Bringmann, Cassis & Fischer, FOCS 2023). Real weights: O(nm)O(nm) stood until Fineman's O~(mn8/9)\tilde O(mn^{8/9}) (STOC 2024).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Within each round, Bellman–Ford may relax the edges in any order. Why does the order not affect correctness?

  1. Because estimates only decrease, the bound d[v]≤δi(s,v)d[v] \le \delta_i(s, v) after round ii holds for every order; the order only changes how quickly the estimates converge
  2. Because every order relaxes the edges of a shortest path in path order
  3. It does affect correctness: the edges must be sorted by weight
  4. Because Bellman–Ford recomputes all estimates from scratch in each round
Show the answer

A. Because estimates only decrease, the bound d[v]≤δi(s,v)d[v] \le \delta_i(s, v) after round ii holds for every order; the order only changes how quickly the estimates converge

The induction only needs d[u]≤δi−1(s,u)d[u] \le \delta_{i-1}(s, u) when the edge u→vu \to v is relaxed in round ii, 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.

Question 2

In round nn, Bellman–Ford still lowers the estimate of a vertex xx. Why walk back nn parent pointers from xx before reading off the cycle?

  1. To compute the weight of the cycle
  2. Because xx may lie after the cycle rather than on it, and nn steps back are sure to land inside a cycle of the parent graph
  3. Because parent pointers are stored in reverse order
  4. To keep the total running time within O(nm)O(nm)
Show the answer

B. Because xx may lie after the cycle rather than on it, and nn steps back are sure to land inside a cycle of the parent graph

The change at xx 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 nn steps, so after nn steps it is inside a cycle; cycles in the parent graph always have negative weight.

Question 3

All pairs on a sparse graph with n=104n = 10^4 vertices, m=5×104m = 5 \times 10^4 edges and some negative weights, but no negative cycle. How do Johnson's algorithm and Floyd–Warshall compare?

  1. They are the same: both are O(n3)O(n^3)
  2. Floyd–Warshall is faster, because Johnson's algorithm runs Dijkstra's algorithm nn times
  3. Johnson's algorithm cannot be used, because of the negative weights
  4. Johnson's algorithm is faster by orders of magnitude: about 2×1092 \times 10^9 steps against 101210^{12}
Show the answer

D. Johnson's algorithm is faster by orders of magnitude: about 2×1092 \times 10^9 steps against 101210^{12}

nm+n2log⁡2n≈5×108+1.3×109≈1.8×109nm + n^2\log_2 n \approx 5 \times 10^8 + 1.3 \times 10^9 \approx 1.8 \times 10^9 for Johnson's algorithm, against n3=1012n^3 = 10^{12} for Floyd–Warshall. On dense graphs, with m≈n2m \approx n^2, the two meet at Θ(n3)\Theta(n^3).

Question 4

A system of constraints xj−xi≤cijx_j - x_i \le c_{ij} has the constraint graph with an edge i→ji \to j of weight cijc_{ij} per constraint, plus a source qq with 0-weight edges to every variable. Bellman–Ford from qq finds no negative cycle. Which assignment satisfies every constraint?

  1. xv=δ(q,v)x_v = \delta(q, v)
  2. xv=−δ(q,v)x_v = -\delta(q, v)
  3. xv=0x_v = 0 for every vv
  4. xvx_v = the number of edges on a shortest path from qq to vv
Show the answer

A. xv=δ(q,v)x_v = \delta(q, v)

The triangle inequality δ(q,j)≤δ(q,i)+cij\delta(q, j) \le \delta(q, i) + c_{ij} is exactly the constraint xj−xi≤cijx_j - x_i \le c_{ij}. Adding the same constant to every xvx_v gives more solutions; if Bellman–Ford had found a negative cycle, summing its constraints would give 0≤0 \le 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 O~(mn8/9)\tilde O(mn^{8/9}) Time," STOC (2024).