← Back to Algorithms, page 4

algorithms-0075 · Hard senior

Bellman-Ford basics: compute shortest paths with negative edge weights, detect a reachable negative cycle, and limit routes to at most k edges.

Relax every edge V - 1 times; after round i, every shortest path that uses at most i edges is correct. One extra round that still improves a distance proves a negative cycle reachable from the source. Cost is O(V * E). Relaxing from a copy of the previous round limits paths to one more edge per round, which solves cheapest flights within k stops.

Full answer

Problem

Part 1: given n nodes, directed edges (u, v, w) where w may be negative, and a source, return the shortest distance to every node and whether a negative cycle is reachable from the source.

Part 2: cheapest flight from src to dst using at most k stops (k + 1 edges), or -1.

Example: edges (0,1,4), (0,2,5), (1,2,-3), (2,3,2) from 0 give [0, 4, 1, 3] and no negative cycle. With flights 0-1 100, 1-2 100, 2-3 100, 0-3 500, 1-3 600, the cheapest route from 0 to 3 within 1 stop costs 500, and within 2 stops it costs 300.

Constraints: up to a few thousand nodes and edges (the algorithm is O(V * E)).

Brute force

Enumerate simple paths with DFS and keep the minimum per node: exponential. Dijkstra is not a fallback here, because it can finalise a node too early when a later negative edge would make it cheaper.

Optimal approach

  1. dist[src] = 0, others infinity.
  2. Repeat V - 1 times: for every edge (u, v, w) with dist[u] finite, set dist[v] = min(dist[v], dist[u] + w). Stop early if a round changes nothing.
  3. One more pass: if any edge can still be relaxed, a negative cycle is reachable.

For the k-stops version, run k + 1 rounds, and in each round read from the previous round's array and write into a copy, so that a single round cannot chain several new edges.

Why it works

By induction, after round i every node whose shortest path uses at most i edges has its correct distance, because the last edge of that path was relaxed in round i. Without negative cycles, shortest paths are simple and use at most V - 1 edges, so V - 1 rounds are enough. If a distance still improves afterwards, some path with V or more edges is cheaper, which requires repeating a node, and that repeated loop must have negative total weight.

Complexity

O(V * E) time, O(V) space. The k-stops version is O(k * E) time and O(V) space with two arrays.

Code

python
import random


def bellman_ford(n, edges, src):
    """Shortest paths with negative weights allowed. O(V * E).
    Returns (dist, has_negative_cycle_reachable_from_src)."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(n - 1):               # a shortest simple path has at most n-1 edges
        changed = False
        for u, v, w in edges:
            if dist[u] != INF and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break                        # early exit: already stable
    for u, v, w in edges:                # one more round: any improvement means a negative cycle
        if dist[u] != INF and dist[u] + w < dist[v]:
            return dist, True
    return dist, False


def cheapest_within_k_stops(n, flights, src, dst, k):
    """At most k+1 edges. Relax from a copy each round so one round adds only one edge."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(k + 1):
        nxt = dist[:]
        for u, v, w in flights:
            if dist[u] != INF and dist[u] + w < nxt[v]:
                nxt[v] = dist[u] + w
        dist = nxt
    return -1 if dist[dst] == INF else dist[dst]


def brute(n, edges, src):
    """Enumerate simple paths by DFS (valid reference when no negative cycle exists)."""
    best = [float("inf")] * n
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))

    def walk(u, cost, on_path):
        best[u] = min(best[u], cost)
        for v, w in adj[u]:
            if v not in on_path:
                on_path.add(v)
                walk(v, cost + w, on_path)
                on_path.remove(v)
    walk(src, 0, {src})
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)]
    assert bellman_ford(4, edges, 0) == ([0, 4, 1, 3], False)
    assert bellman_ford(3, [(0, 1, 1), (1, 2, -2), (2, 1, 1)], 0)[1] is True
    assert bellman_ford(3, [(1, 2, -2), (2, 1, 1)], 0)[1] is False   # cycle not reachable from 0
    flights = [(0, 1, 100), (1, 2, 100), (2, 3, 100), (0, 3, 500), (1, 3, 600)]
    assert cheapest_within_k_stops(4, flights, 0, 3, 1) == 500
    assert cheapest_within_k_stops(4, flights, 0, 3, 2) == 300
    assert cheapest_within_k_stops(4, flights, 3, 0, 5) == -1
    rng = random.Random(75)
    tested = 0
    while tested < 300:
        n = rng.randint(1, 7)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(-3, 8)) for _ in range(rng.randint(0, 12))]
        dist, neg = bellman_ford(n, es, 0)
        if not neg:
            assert dist == brute(n, es, 0)
            tested += 1
    print("all tests passed")

Save as b75_bellman_ford.py and run python3 b75_bellman_ford.py. It prints all tests passed (Python 3.13.5).

Edge cases

Negative cycle not reachable from the source (does not affect the answer; the code reports False). Unreachable nodes (skip relaxing from infinity, otherwise inf + negative comparisons cause errors in other languages). Self-loop with negative weight (a negative cycle). Zero edges.

Pattern

Dynamic programming over the number of edges. Related: SPFA (queue-based Bellman-Ford, faster on average but same worst case), currency arbitrage detection (log of rates, negative cycle), difference constraints systems, and Johnson's algorithm, which uses one Bellman-Ford run to reweight edges for Dijkstra.

python
import random


def bellman_ford(n, edges, src):
    """Shortest paths with negative weights allowed. O(V * E).
    Returns (dist, has_negative_cycle_reachable_from_src)."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(n - 1):               # a shortest simple path has at most n-1 edges
        changed = False
        for u, v, w in edges:
            if dist[u] != INF and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break                        # early exit: already stable
    for u, v, w in edges:                # one more round: any improvement means a negative cycle
        if dist[u] != INF and dist[u] + w < dist[v]:
            return dist, True
    return dist, False


def cheapest_within_k_stops(n, flights, src, dst, k):
    """At most k+1 edges. Relax from a copy each round so one round adds only one edge."""
    INF = float("inf")
    dist = [INF] * n
    dist[src] = 0
    for _ in range(k + 1):
        nxt = dist[:]
        for u, v, w in flights:
            if dist[u] != INF and dist[u] + w < nxt[v]:
                nxt[v] = dist[u] + w
        dist = nxt
    return -1 if dist[dst] == INF else dist[dst]


def brute(n, edges, src):
    """Enumerate simple paths by DFS (valid reference when no negative cycle exists)."""
    best = [float("inf")] * n
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))

    def walk(u, cost, on_path):
        best[u] = min(best[u], cost)
        for v, w in adj[u]:
            if v not in on_path:
                on_path.add(v)
                walk(v, cost + w, on_path)
                on_path.remove(v)
    walk(src, 0, {src})
    return best


if __name__ == "__main__":
    edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)]
    assert bellman_ford(4, edges, 0) == ([0, 4, 1, 3], False)
    assert bellman_ford(3, [(0, 1, 1), (1, 2, -2), (2, 1, 1)], 0)[1] is True
    assert bellman_ford(3, [(1, 2, -2), (2, 1, 1)], 0)[1] is False   # cycle not reachable from 0
    flights = [(0, 1, 100), (1, 2, 100), (2, 3, 100), (0, 3, 500), (1, 3, 600)]
    assert cheapest_within_k_stops(4, flights, 0, 3, 1) == 500
    assert cheapest_within_k_stops(4, flights, 0, 3, 2) == 300
    assert cheapest_within_k_stops(4, flights, 3, 0, 5) == -1
    rng = random.Random(75)
    tested = 0
    while tested < 300:
        n = rng.randint(1, 7)
        es = [(rng.randrange(n), rng.randrange(n), rng.randint(-3, 8)) for _ in range(rng.randint(0, 12))]
        dist, neg = bellman_ford(n, es, 0)
        if not neg:
            assert dist == brute(n, es, 0)
            tested += 1
    print("all tests passed")

Bellman-Ford with early exit and negative-cycle check, the k-stops variant, and a simple-path DFS reference used on random graphs with no negative cycle.

Complexity

Time: O(V * E); O(k * E) for k stops. Space: O(V). Early exit helps on typical inputs but does not change the worst case.

By level

Fresher: Explains relaxation and why V - 1 rounds are enough on a small graph with a negative edge. Knows that Dijkstra fails with negative weights.

Mid: Implements negative-cycle detection and the k-stops variant with the copy trick, explaining why in-place updates are wrong there. States O(V * E).

Senior: Discusses SPFA, Johnson's algorithm and difference constraints, and propagating minus infinity to nodes affected by a cycle. Applies negative-cycle detection to arbitrage and constraint checking.

Key points

  • Relax all edges V - 1 times
  • Round i fixes paths with at most i edges
  • Extra improving round means a reachable negative cycle
  • Copy the array per round to limit edges
  • O(V * E)

Common mistakes

  • Using Dijkstra with negative weights
  • Relaxing from infinity
  • Updating in place for the k-stops version
  • Reporting cycles that are not reachable as affecting distances

Follow-ups

  • How do you mark every node whose distance is minus infinity because of a negative cycle?
  • How would you detect currency arbitrage?
  • How does Johnson's algorithm use Bellman-Ford?

Tips

  • State the induction on edge count
  • Explain the copy trick for k stops
  • Mention when to use Dijkstra instead

Evaluation rubric

  • Correct relaxation rounds
  • Correct negative-cycle detection
  • Correct k-stops variant
  • Correct complexity