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- A. 5 4 2 3 1 0
- B. 5 2 3 4 0 1
- C. 4 5 2 0 3 1
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 0, digitsA = 0…
- What will be the output of the following pseudocode? Function odd(Integer n) if (n == 0) return 0 end if return odd(n - 1) + 2 n - 1 End…
- What will be the output of the following pseudocode? ((mask >> i) & 1 is evaluated before ==; ^ is XOR) Integer a[3] = {5, 1, 6}, total =…
- What will be the output of the following pseudocode? (+ joins strings) String s = "PAYPALISHIRING" Integer rows = 3, r = 0, step = 1…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[5] = {1, 3, 5, 4, 2}, n = 5 Integer i = n - 2…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[9] = {3, 2, 3, 1, 2, 4, 5, 5, 6}, k = 4 sort a…