Medium interview relevanceRoadmap: Advanced
TimeO(V · E)
SpaceO(V)

Why it costs this much

Each of the V − 1 rounds relaxes all E edges.

Code

def bellman_ford(n, edges, src):           # edges = [(u, v, w), ...]
    dist = [float("inf")] * n
    dist[src] = 0
    for _ in range(n - 1):                 # V - 1 rounds
        for u, v, w in edges:              # E edges per round: O(V * E) total
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
    return dist

Common pitfalls

It is slow on large graphs. A negative cycle makes shortest paths undefined, so run one extra round: if any distance still drops, a negative cycle exists.

Operation by operation

OperationBestAverageWorstSpace
Bellman-Ford shortest pathO(E) with an early exitO(V · E)O(V · E)O(V)

Bellman-Ford shortest path. Relaxes every edge up to V−1 times. Handles negative weights and detects negative cycles.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list