Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with Bellman–Ford.

Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with Bellman–Ford.
import heapq
def dij(n, edges, s):
    adj = [[] for _ in range(n)]
    for u, v, w in edges: adj[u].append((v, w))
    d = [float("inf")] * n; d[s] = 0; done = [False] * n; h = [(0, s)]
    while h:
        du, u = heapq.heappop(h)
        if done[u]: continue
        done[u] = True
        for v, w in adj[u]:
            if not done[v] and du + w < d[v]: d[v] = du + w; heapq.heappush(h, (d[v], v))
    return d
def bf(n, edges, s):
    d = [float("inf")] * n; d[s] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if d[u] + w < d[v]: d[v] = d[u] + w
    return d
E = [(0, 1, 2), (0, 2, 5), (2, 1, -4), (1, 3, 3)]
print(dij(4, E, 0), bf(4, E, 0))
What is printed?
  1. A. [0, 1, 5, 4] [0, 1, 5, 4]
  2. B. [0, 2, 5, 5] [0, 1, 5, 4]
  3. C. [0, 1, 5, 5] [0, 1, 5, 4]
  4. D. [0, 2, 5, 5] [0, 2, 5, 5]

Correct answer: B. [0, 2, 5, 5] [0, 1, 5, 4]

Dijkstra pops node 1 with distance 2 and finalises it, then node 3 at 5; only later does node 2 (distance 5) reveal 0 → 2 → 1 = 1, but node 1 is already done, so d[1] stays 2 and d[3] stays 5. Bellman–Ford relaxes every edge n − 1 times and gets 1 and 4. Dijkstra's greedy proof needs non-negative weights; with negative edges (and no negative cycle) use Bellman–Ford/SPFA, or Johnson's reweighting for many sources.

More Coding Interview Problems questions

Exams that ask this topic