Bellman Ford Algorithm Negative Weights in DSA Python - Time & Space Complexity
We want to understand how the Bellman Ford algorithm's running time changes as the graph size grows.
Specifically, how does the number of edges and vertices affect the work done?
Analyze the time complexity of the following Bellman Ford code snippet.
def bellman_ford(graph, source):
distance = {v: float('inf') for v in graph}
distance[source] = 0
for _ in range(len(graph) - 1):
for u in graph:
for v, w in graph[u]:
if distance[u] + w < distance[v]:
distance[v] = distance[u] + w
return distance
This code finds shortest paths from one node to all others, even with negative edge weights.
Look at the loops that repeat work:
- Primary operation: Checking and updating distances for each edge.
- How many times: The outer loop runs (number of vertices - 1) times.
- Inside, it loops over all vertices, and for each vertex, over all its edges.
- This means the edge relaxation step happens many times, dominating the work.
As the graph grows, the number of vertices (V) and edges (E) increase.
| Input Size (V, E) | Approx. Operations |
|---|---|
| V=10, E=20 | ~ 9 * 20 = 180 |
| V=100, E=500 | ~ 99 * 500 = 49,500 |
| V=1000, E=5000 | ~ 999 * 5000 = 4,995,000 |
Pattern observation: The work grows roughly by multiplying vertices and edges, so doubling vertices or edges roughly doubles the work.
Time Complexity: O(V * E)
This means the time to finish grows proportionally to the number of vertices times the number of edges.
[X] Wrong: "Bellman Ford runs in O(E) time because it just checks edges."
[OK] Correct: The algorithm repeats edge checks (relaxations) for each vertex minus one, so it multiplies the work by the number of vertices.
Understanding this time complexity helps you explain why Bellman Ford is slower than other shortest path algorithms but necessary for graphs with negative weights.
"What if we stopped the algorithm early when no distance updates happen in a full pass? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand Bellman-Ford's goal
The Bellman-Ford algorithm is designed to find shortest paths from one source vertex to all other vertices in a graph, even if some edges have negative weights.Step 2: Compare with other algorithms
Unlike Dijkstra's algorithm, Bellman-Ford can handle negative weights and also detect negative weight cycles.Final Answer:
To find the shortest path from a single source to all vertices, even with negative weights -> Option DQuick Check:
Bellman-Ford finds shortest paths with negative weights [OK]
- Confusing Bellman-Ford with Dijkstra's algorithm
- Thinking it finds longest paths
- Assuming it only detects cycles
Solution
Step 1: Initialize distances to infinity
We set all distances to infinity to represent unknown paths initially.Step 2: Set source distance to zero
The distance from the source vertex to itself is zero, so dist[src] = 0.Final Answer:
dist = [float('inf')] * n; dist[src] = 0 -> Option AQuick Check:
Initialize all to infinity, source to zero [OK]
- Setting all distances to zero
- Setting source distance to infinity
- Using null instead of infinity
n = 4 edges = [(0,1,4), (0,2,5), (1,2,-3), (2,3,4)] src = 0
Solution
Step 1: Initialize distances
dist = [0, inf, inf, inf]Step 2: Relax edges repeatedly
Iteration 1: dist[1] = 4, dist[2] = 5; then dist[2] = min(5, 4 + (-3)) = 1; dist[3] = dist[2] + 4 = 5 Iteration 2: No further updatesFinal Answer:
[0, 4, 1, 5] -> Option CQuick Check:
Relax edges 3 times, get distances [0,4,1,5] [OK]
- Not updating dist[2] with negative edge
- Calculating dist[3] incorrectly
- Stopping relaxation too early
def bellman_ford(n, edges, src):
dist = [float('inf')] * n
dist[src] = 0
for _ in range(n):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
Solution
Step 1: Check loop iterations
Bellman-Ford requires relaxing edges exactly n-1 times to guarantee shortest paths.Step 2: Identify the error
The code runs the outer loop n times, which is one extra iteration and can cause incorrect detection of negative cycles or unnecessary work.Final Answer:
The outer loop should run n-1 times, not n times -> Option AQuick Check:
Outer loop runs n-1 times [OK]
- Running outer loop n times instead of n-1
- Misinitializing distances
- Confusing relaxation condition
Solution
Step 1: Calculate cycle weight sum
The cycle is 0->1->2->0 with weights 1 + (-1) + (-1) = -1, which is negative.Step 2: Understand Bellman-Ford behavior
Bellman-Ford detects negative weight cycles by checking for further relaxation after n-1 iterations.Step 3: Conclusion
Since the cycle sum is negative, Bellman-Ford will detect this negative weight cycle.Final Answer:
It will detect a negative weight cycle because the cycle sum is negative -> Option BQuick Check:
Negative cycle sum triggers detection [OK]
- Assuming no negative cycles exist
- Thinking algorithm crashes on negative cycles
- Confusing cycle detection with path finding
Ready to prove it?
Pass the test and this pattern moves unknown
