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

Problem: Dijkstra's algorithm (array-based, pick the unvisited vertex with smallest tentative distance each round) computes shortest distances from vertex 0 on this undirected weighted graph.

Problem: Dijkstra's algorithm (array-based, pick the unvisited vertex with smallest tentative distance each round) computes shortest distances from vertex 0 on this undirected weighted graph.
edges = [(1,4,9),(1,2,6),(2,0,8),(1,4,6),(2,3,11),(1,0,11),(2,3,3)]  # (u, v, weight)
What distance array (index 0 to 4) does it produce?
  1. A. 1, 12, 9, 12, 18
  2. B. 0, 11, 8, 11, 17
  3. C. 0, 1, 1, 2, 2
  4. D. 17, 11, 8, 11, 0

Correct answer: B. 0, 11, 8, 11, 17

Repeatedly finalising the closest unvisited vertex and relaxing its edges gives the true shortest-path distances [0, 11, 8, 11, 17] here. Counting edges (hops) instead of summing weights, [0, 1, 1, 2, 2], ignores the actual edge weights and is wrong whenever they aren't all equal.

More Coding Interview Problems questions

Exams that ask this topic