Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford.

Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford.
import heapq
g = {'S': [('A', 2), ('B', 5)], 'A': [('C', 1)], 'B': [('A', -4)], 'C': []}
def dijkstra(s):
    dist, done, h = {s: 0}, set(), [(0, s)]
    while h:
        d, u = heapq.heappop(h)
        if u in done: continue
        done.add(u)
        for v, w in g[u]:
            if v not in done and d + w < dist.get(v, 1e9):
                dist[v] = d + w; heapq.heappush(h, (dist[v], v))
    return dist
def bellman(s):
    dist = {v: 1e9 for v in g}; dist[s] = 0
    for _ in range(len(g) - 1):
        for u in g:
            for v, w in g[u]: dist[v] = min(dist[v], dist[u] + w)
    return dist
print(dijkstra('S')['C'], bellman('S')['C'])
What is printed?
  1. A. 3 3
  2. B. 3 2
  3. C. -1 -1
  4. D. 1 3

Correct answer: B. 3 2

Dijkstra finalises A at distance 2 and C at 3 before it ever pops B (5); the cheaper route S→B→A (5 − 4 = 1) arrives too late because A is already 'done'. Bellman–Ford relaxes all edges repeatedly and finds C = 1 + 1 = 2.

More Coding Interview Problems questions

Exams that ask this topic