Data Structures & AlgorithmsHardProduct Company SDE · graph round

Problem: Using Dijkstra from node 0 on the undirected graph with edges (0,1,2), (1,2,2), (0,2,5), (2,3,1), how many nodes have shortest distance at most 5? Run the code.

Problem: Using Dijkstra from node 0 on the undirected graph with edges (0,1,2), (1,2,2), (0,2,5), (2,3,1), how many nodes have shortest distance at most 5? Run the code.
import heapq
edges = [(0, 1, 2), (1, 2, 2), (0, 2, 5), (2, 3, 1)]
g = [[] for _ in range(4)]
for u, v, w in edges:
    g[u].append((v, w))
    g[v].append((u, w))
d = [float('inf')] * 4
d[0] = 0
pq = [(0, 0)]
while pq:
    du, u = heapq.heappop(pq)
    if du > d[u]:
        continue
    for v, w in g[u]:
        if du + w < d[v]:
            d[v] = du + w
            heapq.heappush(pq, (d[v], v))
print(sum(1 for x in d if x <= 5))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 2
  4. D. 1

Correct answer: A. 4

The distances are 0, 2, 4 and 5 for nodes 0 to 3 (0-1-2-3 costs 5), so all four are within 5.

More Coding Interview Problems questions

Exams that ask this topic