ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// directed graph with edge weights
Edges: A->B 4, A->C 1, C->B 2, B->D 1, C->D 5, D->E 3
dist[A] = 0, all others = infinity
repeat until every vertex is finalised
    pick the unfinalised vertex u with the smallest dist and finalise it
    for (each edge u->v with weight w)
        if (dist[u] + w < dist[v]) dist[v] = dist[u] + w
    end for
end repeat
Print dist[B], dist[D], dist[E]
  1. A. 4 5 8
  2. B. 3 4 7
  3. C. 3 6 9
  4. D. 4 6 9

Correct answer: B. 3 4 7

Dijkstra: finalise A (0), then C (1), which improves B to 3 and D to 6; then B (3) improves D to 4; then D (4) gives E = 7. Output 3 4 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic