Data Structures & AlgorithmsHardProduct Company SDE pattern

Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)?

Bellman–Ford from vertex 0 with a negative edge. What is printed (distances, and whether a negative cycle exists)?
edges = [(0, 1, 6), (0, 2, 7), (1, 2, 8), (1, 3, 5), (1, 4, -4), (2, 3, -3), (2, 4, 9), (3, 1, -2), (4, 0, 2), (4, 3, 7)]
n = 5; INF = float('inf'); d = [0] + [INF] * (n - 1)
for _ in range(n - 1):
    for u, v, w in edges:
        if d[u] + w < d[v]: d[v] = d[u] + w
neg = any(d[u] + w < d[v] for u, v, w in edges)
print(d, neg)
  1. A. [0, 6, 7, 4, 2] False
  2. B. [0, 2, 7, 4, -2] True
  3. C. [0, 2, 7, 4, -2] False
  4. D. [0, 2, 7, 11, -2] False

Correct answer: C. [0, 2, 7, 4, -2] False

Relax every edge V − 1 = 4 times. 0 → 2 (7) → 3 (4) → 1 (2) → 4 (−2). A further pass that still improves a distance would mean a negative cycle; here none does. Dijkstra would finalise vertex 1 at 6 too early. O(VE).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic