Skip to content
Preptima
mediumCodingConceptMidSenior

You are given a set of tasks and their prerequisites. Produce a valid execution order, or report that none exists.

Topological sort produces an order only for a directed acyclic graph. Kahn's algorithm removes zero-in-degree nodes and detects a cycle when fewer than all nodes are emitted; DFS detects a cycle with a back edge into the active stack. Use this GRAPHS answer to show the decision, trade-off, and evidence rather than a memorised definition.

6 min readUpdated 2026-08-15

Answer

Short answer

Topological sort orders tasks only when the prerequisite graph has no directed cycle. Use Kahn's algorithm by repeatedly emitting zero-in-degree nodes; if nodes remain, a cycle blocked the order. A DFS version pushes nodes after descendants and treats an edge to the active stack as the cycle signal.

Was this answer helpful?

Likely follow-ups

  • Return the lexicographically smallest valid order. What does that cost you?
  • Report the actual cycle, not just its existence.
  • Why does undirected cycle detection need a different rule from the directed case?
  • Tasks now have durations and can run in parallel. How do you find the earliest finish time?

Related questions

Related Topics