Bird
Raised Fist0
DSA Typescriptprogramming

Bellman Ford Algorithm Negative Weights in DSA Typescript

Choose your learning style10 modes available
Mental Model
We find the shortest path from one point to all others even if some paths have negative costs, by checking all paths multiple times.
Analogy: Imagine you want to find the cheapest way to travel from your home to many friends' houses. Some roads might give you discounts (negative costs). You keep checking all roads several times to make sure you found the cheapest routes.
Graph with nodes and edges:

  (A)
  /  \
-1   4
 /     \
(B)---3-->(C)

Edges have weights, some negative (-1).
Dry Run Walkthrough
Input: Graph with edges: A->B (-1), A->C (4), B->C (3), B->A (2), C->B (5); start at A
Goal: Find shortest distances from A to all nodes, handling negative weights correctly
Step 1: Initialize distances: A=0, B=∞, C=∞
Distances: A=0, B=∞, C=∞
Why: Start with zero distance to start node and infinity to others
Step 2: Relax edges first time: update B to -1 via A->B, update C to 4 via A->C then to 2 via B->C (B=-1 + 3=2)
Distances: A=0, B=-1, C=2
Why: Check all edges to find better paths from start
Step 3: Relax edges second time: no changes
Distances: A=0, B=-1, C=2
Why: Check again, no shorter paths found using updated distances
Step 4: Relax edges third time: no changes, distances stable
Distances: A=0, B=-1, C=2
Why: No further improvements, shortest paths found
Result:
Distances: A=0, B=-1, C=2
Annotated Code
DSA Typescript
class Edge {
  constructor(public from: string, public to: string, public weight: number) {}
}

class Graph {
  edges: Edge[] = [];
  vertices: Set<string> = new Set();

  addEdge(from: string, to: string, weight: number) {
    this.edges.push(new Edge(from, to, weight));
    this.vertices.add(from);
    this.vertices.add(to);
  }
}

function bellmanFord(graph: Graph, start: string): Map<string, number> | null {
  const dist = new Map<string, number>();

  // Initialize distances
  for (const v of graph.vertices) {
    dist.set(v, Infinity);
  }
  dist.set(start, 0);

  const V = graph.vertices.size;

  // Relax edges V-1 times
  for (let i = 1; i <= V - 1; i++) {
    let updated = false;
    for (const edge of graph.edges) {
      const uDist = dist.get(edge.from)!;
      const vDist = dist.get(edge.to)!;
      if (uDist !== Infinity && uDist + edge.weight < vDist) {
        dist.set(edge.to, uDist + edge.weight);
        updated = true;
      }
    }
    if (!updated) break; // No changes, stop early
  }

  // Check for negative weight cycles
  for (const edge of graph.edges) {
    const uDist = dist.get(edge.from)!;
    const vDist = dist.get(edge.to)!;
    if (uDist !== Infinity && uDist + edge.weight < vDist) {
      return null; // Negative cycle detected
    }
  }

  return dist;
}

// Driver code
const graph = new Graph();
graph.addEdge('A', 'B', -1);
graph.addEdge('A', 'C', 4);
graph.addEdge('B', 'C', 3);
graph.addEdge('B', 'A', 2);
graph.addEdge('C', 'B', 5);

const distances = bellmanFord(graph, 'A');
if (distances === null) {
  console.log('Graph contains a negative weight cycle');
} else {
  for (const [vertex, distance] of distances.entries()) {
    console.log(`${vertex}: ${distance}`);
  }
}
for (const v of graph.vertices) { dist.set(v, Infinity); } dist.set(start, 0);
Initialize all distances to infinity except start node to zero
for (let i = 1; i < V; i++) { for (const edge of graph.edges) { if (uDist !== Infinity && uDist + edge.weight < vDist) { dist.set(edge.to, uDist + edge.weight); updated = true; } } if (!updated) break; }
Relax all edges repeatedly to update shortest distances
for (const edge of graph.edges) { if (uDist !== Infinity && uDist + edge.weight < vDist) { return null; } }
Detect negative weight cycles by checking for further improvements
OutputSuccess
A: 0 B: -1 C: 2
Complexity Analysis
Time: O(V * E) because we relax all edges V-1 times where V is vertices and E is edges
Space: O(V) to store distances for each vertex
vs Alternative: Unlike Dijkstra which fails with negative weights, Bellman-Ford handles them but is slower due to repeated edge checks
Edge Cases
Graph with negative weight cycle
Algorithm detects cycle and returns null
DSA Typescript
if (uDist !== Infinity && uDist + edge.weight < vDist) { return null; }
Graph with single vertex and no edges
Distance to start is zero, others infinity (none here)
DSA Typescript
for (const v of graph.vertices) { dist.set(v, Infinity); } dist.set(start, 0);
Graph with disconnected vertices
Distances to unreachable vertices remain infinity
DSA Typescript
if (uDist !== Infinity && uDist + edge.weight < vDist)
When to Use This Pattern
When you need shortest paths but edges can have negative weights, use Bellman-Ford because it handles negatives and detects cycles.
Common Mistakes
Mistake: Stopping after one pass of edge relaxation
Fix: Relax edges V-1 times to ensure shortest paths are found
Mistake: Not checking for negative weight cycles
Fix: Add a final check for further distance improvements to detect cycles
Summary
Finds shortest paths from one node to all others even with negative edge weights.
Use when graph edges can have negative weights and you need to detect negative cycles.
Keep relaxing all edges multiple times to update distances and detect cycles.

Practice

(1/5)
1. What is the main advantage of the Bellman-Ford algorithm compared to Dijkstra's algorithm?
easy
A. It uses less memory.
B. It runs faster on all graphs.
C. It can handle graphs with negative weight edges.
D. It only works on directed acyclic graphs.

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    It can handle graphs with negative weight edges. -> Option C
  4. Quick Check:

    Negative weights handled = A [OK]
Hint: Bellman-Ford works with negative edges, Dijkstra doesn't [OK]
Common Mistakes:
  • Thinking Bellman-Ford is always faster
  • Believing it uses less memory
  • Assuming it only works on acyclic graphs
2. Which of the following is the correct TypeScript syntax to initialize the distance array for Bellman-Ford with infinity except the source node set to 0?
easy
A. const dist = new Array(n).fill(Infinity); dist[source] = 0;
B. const dist = Array(n).fill(0); dist[source] = Infinity;
C. const dist = new Array(n).fill(0); dist[source] = 0;
D. const dist = new Array(n).fill(-Infinity); dist[source] = 0;

Solution

  1. Step 1: Initialize distances with Infinity

    We start with all distances as Infinity to represent unknown paths, except the source which is 0.
  2. Step 2: Correct syntax for array initialization

    Using new Array(n).fill(Infinity) creates an array of size n filled with Infinity, then setting dist[source] = 0 sets the source distance correctly.
  3. Final Answer:

    const dist = new Array(n).fill(Infinity); dist[source] = 0; -> Option A
  4. Quick Check:

    Initialize with Infinity except source 0 = C [OK]
Hint: Fill array with Infinity, then set source to 0 [OK]
Common Mistakes:
  • Filling with 0 instead of Infinity
  • Setting source distance to Infinity
  • Using -Infinity which is incorrect
3. Consider the following TypeScript code snippet implementing one iteration of edge relaxation in Bellman-Ford:
for (const [u, v, w] of edges) {
  if (dist[u] !== Infinity && dist[u] + w < dist[v]) {
    dist[v] = dist[u] + w;
  }
}
console.log(dist);
If edges = [[0,1,4],[1,2,-2],[0,2,5]] and initial dist = [0, Infinity, Infinity], what will be the output after this iteration?
medium
A. [0, 4, 5]
B. [0, 5, 3]
C. [0, Infinity, Infinity]
D. [0, 4, 2]

Solution

  1. Step 1: Relax edge (0,1,4)

    dist[0] = 0, 0 + 4 = 4 < dist[1] (Infinity), so dist[1] = 4.
  2. Step 2: Relax edge (1,2,-2)

    dist[1] = 4, 4 + (-2) = 2 < dist[2] (Infinity), so dist[2] = 2.
  3. Step 3: Relax edge (0,2,5)

    dist[0] = 0, 0 + 5 = 5 < dist[2] (2)? No, so no update.
  4. Final Answer:

    [0, 4, 2] -> Option D
  5. Quick Check:

    Relax edges updates dist to [0,4,2] [OK]
Hint: Relax edges in order, update dist if smaller [OK]
Common Mistakes:
  • Not updating dist[2] after second edge
  • Updating dist[2] incorrectly on last edge
  • Ignoring initial Infinity checks
4. The following TypeScript code attempts to detect a negative weight cycle after Bellman-Ford iterations:
for (const [u, v, w] of edges) {
  if (dist[u] + w < dist[v]) {
    console.log('Negative cycle detected');
  }
}
What is the bug in this code snippet?
medium
A. It does not check if dist[u] is Infinity before comparison.
B. It should update dist[v] inside the loop.
C. It should use <= instead of < in the condition.
D. It should run inside the main relaxation loop.

Solution

  1. Step 1: Understand the condition for negative cycle detection

    After all relaxation rounds, if any edge can still relax dist[v], a negative cycle exists.
  2. Step 2: Identify missing Infinity check

    If dist[u] is Infinity (unreachable), dist[u] + w is invalid and can cause wrong detection or runtime error.
  3. Final Answer:

    It does not check if dist[u] is Infinity before comparison. -> Option A
  4. Quick Check:

    Check dist[u] !== Infinity before comparing [OK]
Hint: Always check dist[u] !== Infinity before edge relaxation [OK]
Common Mistakes:
  • Forgetting to check dist[u] Infinity
  • Trying to update dist[v] in detection phase
  • Misplacing detection inside main loop
5. You have a graph with edges: [[0,1,1],[1,2,-1],[2,3,-1],[3,1,-1]]. Using Bellman-Ford from source 0, what will be the result after all iterations?
hard
A. Algorithm will run infinitely without detection.
B. Negative cycle detected because the cycle 1->2->3->1 sums to -3.
C. Shortest distances: [0, 1, 2, 3]
D. Shortest distances: [0, 1, 0, -1]

Solution

  1. Step 1: Identify the cycle and its weight

    The cycle 1->2->3->1 has weights 1->2 (-1), 2->3 (-1), 3->1 (-1), total -3, which is negative.
  2. Step 2: Bellman-Ford detects negative cycles

    After |V|-1 iterations, if any edge can still relax distances, it means a negative cycle exists.
  3. Step 3: Result of running Bellman-Ford

    The algorithm will detect the negative cycle and report it instead of giving shortest distances.
  4. Final Answer:

    Negative cycle detected because the cycle 1->2->3->1 sums to -3. -> Option B
  5. Quick Check:

    Negative cycle sum < 0 means detection = D [OK]
Hint: Sum cycle weights; negative sum means cycle detected [OK]
Common Mistakes:
  • Ignoring negative cycle and reporting distances
  • Assuming algorithm runs infinitely
  • Miscomputing cycle weight
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard