Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

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,3,5),(2,1,12),(4,3,5),(1,2,1),(1,0,12),(3,0,2)]  # (u, v, weight)
What distance array (index 0 to 4) does it produce?
  1. A. 0, 7, 8, 2, 7
  2. B. 1, 8, 9, 3, 8
  3. C. 0, 1, 2, 1, 2
  4. D. 7, 2, 8, 7, 0

Correct answer: A. 0, 7, 8, 2, 7

Repeatedly finalising the closest unvisited vertex and relaxing its edges gives the true shortest-path distances [0, 7, 8, 2, 7] here. Counting edges (hops) instead of summing weights, [0, 1, 2, 1, 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