Bellman Ford Algorithm Negative Weights in DSA C++ - 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.
for (int i = 1; i <= V - 1; i++) {
for (auto edge : edges) {
int u = edge.u, v = edge.v, w = edge.w;
if (dist[u] != INT_MAX && dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
}
This code relaxes all edges V-1 times to find shortest paths, even with negative weights.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Relaxing each edge by checking and updating distances.
- How many times: The inner loop runs for all edges, repeated V-1 times (outer loop).
Each vertex causes all edges to be checked once, so work grows with both vertices and edges.
| Input Size (V, E) | Approx. Operations |
|---|---|
| V=10, E=20 | 9 * 20 = 180 |
| V=100, E=200 | 99 * 200 = 19,800 |
| V=1000, E=2000 | 999 * 2000 = 1,998,000 |
Pattern observation: Operations grow roughly by multiplying vertices and edges.
Time Complexity: O(V * E)
This means the time grows by the number of vertices times the number of edges in the graph.
[X] Wrong: "The algorithm runs in O(E) time because it just loops over edges."
[OK] Correct: The edges are checked multiple times--once for each vertex minus one--so the total work depends on both vertices and edges.
Understanding this complexity helps you explain why Bellman Ford is slower than other shortest path algorithms but necessary for graphs with negative weights.
"What if we stop the algorithm early when no distance updates happen in an iteration? How would that affect the time complexity?"
Practice
Bellman Ford algorithm compared to Dijkstra's algorithm?Solution
Step 1: Understand the limitation of Dijkstra's algorithm
Dijkstra's algorithm cannot correctly handle graphs with negative weight edges because it assumes that once a node's shortest path is found, it cannot be improved.Step 2: Identify Bellman Ford's capability
Bellman Ford algorithm can handle negative weight edges and detect negative weight cycles, making it more versatile for such graphs.Final Answer:
It can handle graphs with negative weight edges. -> Option DQuick Check:
Negative weights handled = D [OK]
- Thinking Bellman Ford is always faster than Dijkstra
- Believing Bellman Ford cannot detect negative cycles
- Assuming Bellman Ford only works on acyclic graphs
Solution
Step 1: Understand distance initialization
Distances to all vertices except the source should be set to a very large number (infinity equivalent), here INT_MAX, to represent unknown distance.Step 2: Set source distance to zero
The source vertex distance is zero because the distance from source to itself is zero.Final Answer:
vector<int> dist(V, INT_MAX); dist[src] = 0; -> Option BQuick Check:
Initialize with INT_MAX and source zero = B [OK]
- Setting all distances to zero
- Using INT_MIN which is incorrect for distances
- Not setting source distance to zero
Edges: (0->1, 4), (0->2, 5), (1->2, -3), (2->3, 4), (3->1, 6)
What is the shortest distance from vertex 0 to vertex 3 after running Bellman Ford?
Solution
Step 1: Initialize distances
dist[0]=0, dist[1]=∞, dist[2]=∞, dist[3]=∞.Step 2: Relax edges repeatedly
After first iteration: dist[1]=4, dist[2]=5, dist[3]=∞.
Relax (1->2): dist[2]=4 + (-3) = 1.
Relax (2->3): dist[3]=1 + 4 = 5.
Relax (3->1): dist[1]=min(4, 5 + 6=11) = 4.
Second iteration: No further improvements.
Final dist[3] = 5.Step 3: Check for negative cycles
No negative cycle detected.Final Answer:
5 -> Option AQuick Check:
Shortest path dist to 3 = 5 [OK]
- Not updating distances after negative edge relaxation
- Confusing edge directions
- Stopping relaxation too early
for (int i = 0; i < V; i++) {
for (auto edge : edges) {
if (dist[edge.u] + edge.w < dist[edge.v]) {
dist[edge.v] = dist[edge.u] + edge.w;
}
}
}What is the bug?
Solution
Step 1: Understand Bellman Ford iteration count
Bellman Ford requires relaxing edges exactly V-1 times to find shortest paths without negative cycles.Step 2: Identify the loop error
The code runs the outer loop V times, which is one extra iteration and may cause incorrect detection of negative cycles or unnecessary work.Final Answer:
The outer loop should run V-1 times, not V times. -> Option AQuick Check:
Outer loop count = V-1 [OK]
- Running outer loop V times instead of V-1
- Changing comparison operator incorrectly
- Ignoring distance initialization
(0->1, 1), (1->2, -1), (2->3, -1), (3->1, -1)
What will Bellman Ford detect when run from vertex 0?
Solution
Step 1: Identify the cycle in the graph
The edges (1->2), (2->3), and (3->1) form a cycle with total weight -1 + -1 + -1 = -3, which is negative.Step 2: Understand Bellman Ford's negative cycle detection
Bellman Ford detects negative weight cycles reachable from the source by checking if any edge can still be relaxed after V-1 iterations.Step 3: Conclusion
Since the negative cycle is reachable from vertex 0, Bellman Ford will detect it and report its presence.Final Answer:
A negative weight cycle reachable from source. -> Option CQuick Check:
Negative cycle detected = A [OK]
- Ignoring negative cycles reachable from source
- Assuming algorithm runs infinitely
- Thinking graph is disconnected
Ready to prove it?
Pass the test and this pattern moves unknown
