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.
3 points to say:
- Topological order: each task after what it needs.
- Kahn leaving vertices behind means a cycle.
- 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.