Bellman Ford Algorithm Negative Weights in DSA Java - 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 (Edge edge : edges) {
if (dist[edge.src] + edge.weight < dist[edge.dest]) {
dist[edge.dest] = dist[edge.src] + edge.weight;
}
}
}
This code relaxes all edges repeatedly to find shortest paths, even with negative weights.
Look for loops or repeated steps that take most time.
- Primary operation: Checking and updating distances for each edge (edge relaxation).
- How many times: The outer loop runs V-1 times, and the inner loop runs once for each edge E.
As the number of vertices (V) and edges (E) grow, the total work grows by multiplying these two.
| Input Size (V, E) | Approx. Operations |
|---|---|
| V=10, E=20 | About 9 * 20 = 180 checks |
| V=100, E=200 | About 99 * 200 = 19,800 checks |
| V=1000, E=2000 | About 999 * 2000 = 1,998,000 checks |
Pattern observation: The work grows roughly by multiplying vertices and edges, so doubling both roughly quadruples the work.
Time Complexity: O(V * E)
This means the time grows by the number of vertices times the number of edges, so bigger graphs take more time.
[X] Wrong: "The algorithm runs in O(E) time because it just loops over edges."
[OK] Correct: The edge loop runs many times (V-1), so total work depends on both vertices and edges, not just edges.
Understanding this complexity helps you explain why Bellman Ford is slower than other shortest path algorithms but works with negative weights.
This skill shows you can analyze algorithms beyond just coding them.
"What if we stopped the algorithm early when no distances change in a full pass? How would that affect the time complexity?"
Practice
Bellman-Ford algorithm compared to Dijkstra's algorithm?Solution
Step 1: Understand Dijkstra's limitation
Dijkstra's algorithm cannot handle negative weight edges correctly because it assumes once a node is visited, its shortest path is finalized.Step 2: Bellman-Ford's capability
Bellman-Ford algorithm relaxes edges multiple times and can detect negative weight edges, allowing it to work correctly even with negative weights.Final Answer:
It can handle graphs with negative weight edges. -> Option AQuick Check:
Negative weights handled = A [OK]
- Thinking Bellman-Ford is always faster
- Believing it only works on acyclic graphs
- Confusing memory usage advantages
Solution
Step 1: Initialize distances to max value
We set all distances to Integer.MAX_VALUE to represent infinity initially.Step 2: Set source distance to zero
The source vertex distance is set to 0 because distance from source to itself is zero.Final Answer:
int[] dist = new int[V]; Arrays.fill(dist, Integer.MAX_VALUE); dist[src] = 0; -> Option CQuick Check:
Distance init with max + source zero = D [OK]
- Setting source distance to max instead of zero
- Filling distances with zero instead of max
- Using -1 which is invalid for distances
int[][] edges = {
{0, 1, 4},
{0, 2, 5},
{1, 2, -3},
{2, 3, 4}
};
int V = 4; int src = 0;
What is the shortest distance array after running Bellman-Ford from source 0?Solution
Step 1: Initialize distances
dist = [0, INF, INF, INF]Step 2: Relax edges V-1 times
Iteration 1: - Edge 0->1: dist[1] = min(INF, 0+4) = 4 - Edge 0->2: dist[2] = min(INF, 0+5) = 5 - Edge 1->2: dist[2] = min(5, 4-3) = 1 - Edge 2->3: dist[3] = min(INF, 1+4) = 5 Iteration 2 and 3 do not improve distances further.Final Answer:
[0, 4, 1, 5] -> Option BQuick Check:
Relax edges 3 times, final dist = [0,4,1,5] [OK]
- Not updating dist[2] after edge 1->2 relaxation
- Ignoring negative edge effect
- Stopping after first iteration
for (int i = 0; i < V; i++) {
for (int[] edge : edges) {
int u = edge[0], v = edge[1], w = edge[2];
if (dist[u] != Integer.MAX_VALUE && 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.Step 2: Identify loop error
The code runs the outer loop V times, which is one extra iteration and can cause incorrect behavior 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 loop V times instead of V-1
- Misunderstanding distance initialization condition
- Incorrect edge array indexing
int[][] edges = {
{0, 1, 1},
{1, 2, -1},
{2, 3, -1},
{3, 1, -1}
};
int V = 4; int src = 0;
What will the algorithm detect after V-1 iterations?Solution
Step 1: Identify cycle in graph
Edges 1->2, 2->3, 3->1 form a cycle with total weight -3 (negative).Step 2: Bellman-Ford detects negative cycles
After V-1 iterations, the algorithm checks for further relaxation. If possible, it means a negative weight cycle exists reachable from source.Final Answer:
A negative weight cycle exists reachable from the source. -> Option DQuick Check:
Negative cycle detected = C [OK]
- Assuming no negative cycle despite cycle with negative sum
- Expecting exception on negative weights
- Thinking distances become zero automatically
Ready to prove it?
Pass the test and this pattern moves unknown
