Menu
Coddy logo textTech

How it works?

Lesson 3 of 9 in Coddy's Topological Sort - Graph Algorithms course.

The key quantity is a vertex's in-degree: how many edges point into it. A vertex with in-degree 0 has no unmet prerequisites, so it can go next.

Kahn's Algorithm:

  1. Compute the in-degree of every vertex.
  2. Pick the smallest vertex whose in-degree is 0, append it to the order, and "remove" it.
  3. Removing it decreases the in-degree of each of its out-neighbors by one (some may now reach 0).
  4. Repeat until no in-degree-0 vertex remains. If you placed all n vertices, that is your topological order; if not, the graph has a cycle.

Example with edges [0,1, 0,2, 1,3, 2,3]: start with 0 (in-degree 0), then 1, then 2, then 3, giving [0, 1, 2, 3].

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Topological Sort - Graph Algorithms