SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 22 / 25

Middle

How do you detect a cycle in a directed graph, and where does topological sort show up in backend systems?

Short answer

Kahn's algorithm: keep taking vertices with nothing left that must come first (in-degree 0); leftover vertices mean a cycle. Or three-colour DFS. Both are O(V + E) and give a topological order.

neighbor hits 0YesNoCompute in-degreeof every vertexQueue verticeswith in-degree 0Emit a vertexdecrement neighborsEmitted all V?Topological orderCycle exists

3 points to say:

  1. Topological order: each task after what it needs.
  2. Kahn leaving vertices behind means a cycle.
  3. DFS reaching a vertex still on the stack means a cycle.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.