Code of the Day
AdvancedAdvanced Graphs

Topo sort and cycle detection

Implement Kahn's algorithm with cycle detection, and DFS-based 3-colour cycle marking for directed graphs.

CS FundamentalsAdvanced12 min read
Recommended first
By the end of this lesson you will be able to:
  • Implement Kahn's algorithm returning the topological order and a cycle flag
  • Detect cycles using the output-length shortfall from Kahn's
  • Implement DFS-based cycle detection with 3-colour (white/grey/black) marking

The previous lesson described both algorithms conceptually. Here we implement them and add the cycle-detection logic that makes them useful in practice.

Kahn's algorithm with cycle detection

Python — editable, runs in your browser

How Kahn's detects cycles

When a cycle exists, none of the nodes in the cycle ever reach in-degree 0 (each always has at least one incoming edge from another cycle member). They are never enqueued. The output therefore contains fewer nodes than the full graph. The check len(order) != len(in_degree) catches this in O(1) after the algorithm finishes.

How 3-colour DFS detects cycles

Each node carries a colour:

  • WHITE — not yet visited.
  • GREY — currently on the DFS call stack (we entered but have not finished exploring its descendants).
  • BLACK — fully processed; all descendants are done.

When DFS visits a neighbour that is already GREY, we have found a back edge — a path that leads back to an ancestor in the current stack. That is exactly a cycle. A BLACK neighbour is safe: it was fully explored in an earlier DFS tree and cannot form a new cycle through the current path.

3-colour marking is also the standard approach in many compilers and dependency-resolution engines. The colours map directly to "unvisited", "in progress", and "done" states in iterative implementations, where you push a node twice onto an explicit stack — once to enter (mark grey), once to finish (mark black).

Where to go next

Next: lab — graph algorithms — three problems that put Dijkstra's and topological sort to work: network delay time, course schedule ordering, and a course-prerequisite cycle check.

Finished reading? Mark it complete to track your progress.

On this page