Bellman Ford Algorithm Negative Weights in DSA Javascript - 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 nodes and edges affect the work done?
Analyze the time complexity of the following Bellman Ford code snippet.
function bellmanFord(graph, source) {
const dist = Array(graph.length).fill(Infinity);
dist[source] = 0;
for (let i = 0; i < graph.length - 1; i++) {
for (const [u, v, w] of graph.edges) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
}
}
}
return dist;
}
This code finds shortest paths from a source node to all others, even with negative 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 nodes - 1) times, and the inner loop runs once for each edge.
As the graph grows, the algorithm checks all edges many times.
| Input Size (n nodes, m edges) | Approx. Operations |
|---|---|
| 10 nodes, 20 edges | ~ 9 * 20 = 180 checks |
| 100 nodes, 500 edges | ~ 99 * 500 = 49,500 checks |
| 1000 nodes, 2000 edges | ~ 999 * 2000 = 1,998,000 checks |
Pattern observation: The work grows roughly by multiplying nodes and edges.
Time Complexity: O(n * m)
This means the time grows by the number of nodes times the number of edges in the graph.
[X] Wrong: "The algorithm runs in O(n²) time because it has two loops."
[OK] Correct: The inner loop runs over edges, not nodes, so the time depends on edges (m), not nodes (n) twice.
Understanding this complexity helps you explain how Bellman Ford handles negative weights efficiently compared to other algorithms.
"What if the graph is dense, meaning edges are close to n²? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand Bellman-Ford's goal
The algorithm finds shortest paths from one source vertex to all others, handling negative weights.Step 2: Compare with other algorithms
Dijkstra's algorithm cannot handle negative weights, but Bellman-Ford can and also detects negative 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
All vertices except the source start with distance Infinity to represent unknown paths.Step 2: Set source distance to zero
The source vertex distance is zero because the path from source to itself is zero.Final Answer:
const dist = new Array(V).fill(Infinity); dist[source] = 0; -> Option CQuick Check:
Distance array initialized with Infinity except source = 0 [OK]
- Filling array with zeros instead of Infinity
- Setting source distance to Infinity
- Using map without fill causing undefined values
edges = [[0,1,4],[0,2,5],[1,2,-3],[2,3,4]]Using Bellman-Ford from source 0, what is the distance array after all relaxations?
Solution
Step 1: Initialize distances
dist = [0, Infinity, Infinity, Infinity]Step 2: Relax edges |V|-1 = 3 times
First iteration:
- (0,1,4): dist[1] = 0 + 4 = 4
- (0,2,5): dist[2] = 0 + 5 = 5
- (1,2,-3): dist[2] = min(5, 4 + (-3)) = 1
- (2,3,4): dist[3] = 1 + 4 = 5
dist = [0,4,1,5]
Second and third iterations: no updates.Final Answer:
[0, 4, 1, 5] -> Option AQuick Check:
Distances after relaxations = [0,4,1,5] [OK]
- Not relaxing edges enough times
- Ignoring negative weight edge effect
- Incorrectly updating distances
for (let i = 0; i < V; i++) {
for (const [u, v, w] of edges) {
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.Step 2: Identify off-by-one error
The code runs the outer loop V times, which is one extra iteration and may cause incorrect behavior or unnecessary work.Final Answer:
The outer loop should run V-1 times, not V times -> Option AQuick Check:
Outer loop runs V-1 times in Bellman-Ford [OK]
- Running outer loop V times instead of V-1
- Mixing up edge and vertex iteration
- Wrong relaxation condition
edges = [[0,1,1],[1,2,-1],[2,3,-1],[3,1,-1]]and source 0, what does Bellman-Ford detect after running all relaxations?
Solution
Step 1: Analyze the cycle in the graph
The edges (1->2), (2->3), (3->1) form a cycle with total weight -3 (negative cycle).Step 2: Bellman-Ford detects negative cycles
After V-1 relaxations, one more iteration finds further distance reductions, indicating a negative cycle reachable from source.Final Answer:
Negative cycle detected reachable from source -> Option BQuick Check:
Negative cycle detection triggers on further relaxation [OK]
- Ignoring negative cycle presence
- Assuming zero-weight cycles cause failure
- Thinking distances remain Infinity
Ready to prove it?
Pass the test and this pattern moves unknown
