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 edges: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1
Compute indegree of every vertex 0..5
Set ready = all vertices with indegree 0
while (ready not empty)
    Integer u = smallest vertex in ready
    remove u from ready
    Print u
    for (each edge u->v)
        indegree[v] = indegree[v] - 1
        if (indegree[v] == 0) add v to ready
    end for
end while
  1. A. 5 4 2 3 1 0
  2. B. 5 2 3 4 0 1
  3. C. 4 5 2 0 3 1
  4. D. 4 5 0 2 3 1

Correct answer: D. 4 5 0 2 3 1

Kahn's algorithm always takes the smallest ready vertex. Start: {4, 5} → 4 (0 still waits for 5 and 1 for 3); then 5 frees 2 and 0, and the smaller, 0, goes first; then 2 frees 3, and 3 frees 1. Order 4 5 0 2 3 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic