Bellman Ford Algorithm Negative Weights in DSA C - Time & Space Complexity
We analyze how the Bellman Ford algorithm's running time grows with the size of the graph.
We want to know how the number of edges and vertices affects the work done.
Analyze the time complexity of the following code snippet.
void bellmanFord(int V, int E, int edges[][3], int src, int dist[]) {
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[src] = 0;
for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = edges[j][0];
int v = edges[j][1];
int w = edges[j][2];
if (dist[u] != INT_MAX && dist[u] + w < dist[v])
dist[v] = dist[u] + w;
}
}
}
This code finds shortest paths from a source vertex to all others, even with negative weights.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop over all edges that relaxes distances.
- How many times: This inner loop runs for each vertex minus one times (V-1 times).
The algorithm repeats checking all edges many times, so work grows with both vertices and edges.
| Input Size (V, E) | Approx. Operations |
|---|---|
| V=10, E=20 | About 9 * 20 = 180 |
| V=100, E=500 | About 99 * 500 = 49,500 |
| V=1000, E=2000 | About 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 multiplying the number of vertices and edges in the graph.
[X] Wrong: "The algorithm runs in O(V^2) time because it has two loops over vertices."
[OK] Correct: The inner loop runs over edges, not vertices, so the time depends on edges, not just vertices.
Understanding this complexity helps you explain how Bellman Ford handles negative weights efficiently compared to other algorithms.
"What if we stopped the algorithm early when no distances change in an iteration? How would the time complexity change?"
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: Recognize Bellman-Ford's capability
Bellman-Ford algorithm can handle negative weight edges and detect negative weight cycles, making it more versatile.Final Answer:
It can handle graphs with negative weight edges. -> Option DQuick Check:
Negative weights handled = A [OK]
- Thinking Bellman-Ford is always faster
- Assuming it uses less memory
- Believing it 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), here represented by INT_MAX, to indicate they are initially unreachable.Step 2: Set source distance to zero
The distance to the source vertex itself must be zero because the shortest path from source to source is zero.Final Answer:
int dist[V]; for(int i=0; i -> Option BQuick Check:
Initialize all to max, source to 0 = C [OK]
- Initializing all distances to zero
- Using -1 for unreachable distances
- Setting all distances to source index
edges = [(0,1,4), (0,2,5), (1,2,-3), (2,3,4)] starting from source 0?Solution
Step 1: Initialize distances
dist = [0, INF, INF, INF]Step 2: Relax edges repeatedly
First iteration:
dist[1] = min(INF, 0+4) = 4
dist[2] = min(INF, 0+5) = 5
dist[2] = min(5, 4 + (-3)) = 1
dist[3] = min(INF, 1 + 4) = 5
Second iteration:
dist[1] stays 4
dist[2] stays 1
dist[3] stays 5
No further updates.Final distances:
[0, 4, 1, 5]Final Answer:
[0, 4, 1, 5] -> Option AQuick Check:
Relax edges to update distances = A [OK]
- Not relaxing edges enough times
- Ignoring negative edge effect
- Wrong initial distances
for (int i = 0; i < V; i++) {
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int w = edges[j].weight;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
}Solution
Step 1: Check loop iteration count
Bellman-Ford requires relaxing edges exactly V-1 times to find shortest paths correctly.Step 2: Identify the incorrect loop count
The outer loop runs V times here, which is one extra iteration and unnecessary.Final Answer:
The outer loop should run V-1 times, not V times. -> Option AQuick Check:
Outer loop runs V-1 times = D [OK]
- Running outer loop V times instead of V-1
- Confusing inner loop count with vertex count
- Incorrect weight comparison direction
[(0,1,1), (1,2,-1), (2,3,-1), (3,1,-1)], what will Bellman-Ford detect when run from source 0?Solution
Step 1: Analyze 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 by checking for further relaxation after V-1 iterations. Here, it will detect the negative cycle.Final Answer:
It will detect a negative weight cycle. -> Option CQuick Check:
Negative cycle detected = A [OK]
- Assuming algorithm runs infinitely
- Believing it finds shortest paths despite negative cycle
- Ignoring cycle detection step
Ready to prove it?
Pass the test and this pattern moves unknown
