Data Structures & AlgorithmsHardProduct Company SDE · graph round

Problem: Dijkstra from 0 with edges (0,1,1), (1,3,2), (0,2,4), (2,3,1). Which vertex sequence is the shortest path from 0 to 3? Run the code.

Problem: Dijkstra from 0 with edges (0,1,1), (1,3,2), (0,2,4), (2,3,1). Which vertex sequence is the shortest path from 0 to 3? Run the code.
import heapq
g = {0: [(1, 1), (2, 4)], 1: [(3, 2)], 2: [(3, 1)], 3: []}
dist = {0: 0}
prev = {}
pq = [(0, 0)]
while pq:
    d, u = heapq.heappop(pq)
    if d > dist.get(u, float('inf')):
        continue
    for v, w in g[u]:
        if d + w < dist.get(v, float('inf')):
            dist[v] = d + w
            prev[v] = u
            heapq.heappush(pq, (dist[v], v))
path = [3]
while path[-1] != 0:
    path.append(prev[path[-1]])
print(path[::-1])
What is printed?
  1. A. [0, 2, 3]
  2. B. [0, 1, 3]
  3. C. [0, 1, 2, 3]
  4. D. [0, 2, 1, 3]

Correct answer: B. [0, 1, 3]

The route 0-1-3 costs 3, while 0-2-3 costs 5. Storing parent pointers and walking back from the target recovers the path.

More Coding Interview Problems questions

Exams that ask this topic