Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Kahn's algorithm uses a MIN-heap (smallest available vertex first) on the DAG with edges 3→1, 3→4, 2→4, 4→0, 1→0, 5→2. What topological order does it produce?

  1. A. 3, 5, 1, 2, 4, 0
  2. B. 5, 3, 2, 1, 4, 0
  3. C. 3, 1, 4, 5, 2, 0
  4. D. 3, 1, 5, 2, 4, 0

Correct answer: D. 3, 1, 5, 2, 4, 0

Initially in-degree 0: {3, 5} → take 3; this frees 1 (4 still waits for 2) → heap {1, 5} → take 1 (0 still waits for 4) → take 5 → frees 2 → take 2 → frees 4 → take 4 → frees 0. Order 3, 1, 5, 2, 4, 0. A FIFO queue would take 5 before 1 (3, 5, 1, 2, 4, 0); taking 4 right after 1 ignores its pending edge from 2.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic