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

Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights.

Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights.
import heapq
def dijkstra(n, edges, s):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w)); adj[v].append((u, w))
    dist = [float('inf')] * n; dist[s] = 0; pq = [(0, s)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]: continue
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w; heapq.heappush(pq, (dist[v], v))
    return dist
print(dijkstra(5, [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1), (2, 3, 5), (3, 4, 3)], 0))
What is printed?
  1. A. [0, 3, 1, 4, 7]
  2. B. [0, 4, 1, 5, 8]
  3. C. [0, 3, 1, 6, 9]
  4. D. [0, 3, 1, 4, 8]

Correct answer: A. [0, 3, 1, 4, 7]

0→2 (1), 2→1 (1 + 2 = 3, better than the direct 4), 1→3 (4, better than 2→3 = 6), 3→4 (7). The 'd > dist[u]' check skips stale heap entries. O((V + E) log V).

More Coding Interview Problems questions

Exams that ask this topic