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?- A. 3 3
- B. 3 2
- C. -1 -1
- 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
- Problem: Topological order produced by DFS (append a node after all its descendants, then reverse). python g = {0: [2, 1], 1: [3], 2: [3…
- Problem: Maximum bipartite matching between workers (left) and jobs (right) with Kuhn's augmenting-path algorithm. python adj = {0: [0…
- Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths). python from collections import deque cap = [[0]6 for…
- Problem: Does an undirected connected graph have an Euler path / Euler circuit? (count odd-degree vertices) python from collections import…
- Problem: Count Hamiltonian paths (ordered sequences visiting every vertex once) in a small undirected graph with bitmask DP. python n = 5…
- Problem: Reconstruct an actual longest strictly increasing subsequence with the O(n²) DP and parent pointers (the first maximal end index…