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?- A. [0, 1, 5, 4] [0, 1, 5, 4]
- B. [0, 2, 5, 5] [0, 1, 5, 4]
- C. [0, 1, 5, 5] [0, 1, 5, 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
- Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous…
- Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place…
- Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM…
- Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start). python def…
- Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as…
- A divide-and-conquer routine satisfies T(n) = 4T(n/2) + n² log n. What is its running time?