Data Structures & AlgorithmsVery hardAmazon · Microsoft coding round

Problem: Topological sort is only defined for which kind of graph, and what happens if Kahn's algorithm is run on a graph that violates this?

  1. A. Only a Directed Acyclic Graph (DAG); if a cycle exists, some nodes never reach in-degree 0 and are left out of the output, signalling the cycle
  2. B. Only undirected graphs
  3. C. Any directed graph, cycles included, always producing a valid full order
  4. D. Only trees, never general DAGs

Correct answer: A. Only a Directed Acyclic Graph (DAG); if a cycle exists, some nodes never reach in-degree 0 and are left out of the output, signalling the cycle

A topological order requires no cycles (a DAG); Kahn's algorithm detects a cycle indirectly because any node inside the cycle never has all its incoming edges 'removed', so it never enters the queue, and the final output omits it.

More Coding Interview Problems questions

Exams that ask this topic