Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation pass.

Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation pass.
def bellman(n, edges, src):
    INF = float("inf"); d = [INF] * n; d[src] = 0
    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)
    return d, neg
print(bellman(4, [(0, 1, 4), (0, 2, 5), (1, 3, -3), (2, 1, -2), (3, 2, 6)], 0), bellman(3, [(0, 1, 1), (1, 2, -2), (2, 1, 1)], 0)[1])
What is printed?
  1. A. ([0, 3, 5, 0], False) False
  2. B. ([0, 3, 5, 0], True) True
  3. C. ([0, 4, 5, 1], False) True
  4. D. ([0, 3, 5, 0], False) True

Correct answer: D. ([0, 3, 5, 0], False) True

Shortest paths: 0 → 2 = 5; 0 → 2 → 1 = 5 − 2 = 3 (better than the direct 4); 0 → 2 → 1 → 3 = 0. The cycle 1 → 3 → 2 → 1 weighs −3 + 6 − 2 = +1, so no negative cycle. In the second graph 1 → 2 → 1 weighs −1, so a further pass still relaxes → True. Dijkstra would settle node 1 at 4 too early. O(V·E).

More Coding Interview Problems questions

Exams that ask this topic