Topological sort: DFS order and Kahn's algorithm

Video lessonComing soon

1 Some things must come first

To get dressed, socks go on before shoes. Any order we dress in has to respect that. A college has the same problem with its courses. Here are six courses, numbered 0 to 5. An arrow u → v means course u must be passed before course v can start:

012345
Course 3 needs 1 and 0. Nothing points into 2 or 4

A student wants a plan: all six courses in a line, each one after every course it needs. That plan is a topological order. It is a list of all the vertices in which, for every edge u → v, u comes before v.

There is usually more than one. Both of these plans work:

204112033455
One plan
401122033455
Another plan

The plan 4, 1, 3, 2, 0, 5 does not work. It puts 3 before 0, but the arrow 0 → 3 says 0 comes first. To check a plan, we check every arrow.

Only a DAG has one. Add an arrow 5 → 1, and 1 → 3 → 5 → 1 is a cycle. Then 1 must come before 3, 3 before 5, and 5 before 1. No line of courses can do that. So, as the cycle-detection lesson said, only a directed acyclic graph (DAG) has a topological order. Kahn's algorithm, next, finds one in every DAG.

2 Kahn's algorithm: take what is ready

A student plans it term by term. In term 1, they take every course that needs nothing: 2 and 4. Once those are passed, 0 and 1 need nothing more, so they fill term 2. Then 3 is free, and then 5.

021221334154
The number above each course is its term

Kahn's algorithm does the same, one course at a time. For each vertex, it keeps the in-degree: the number of arrows still coming in. For a course, that is the number of prerequisites not passed yet. A vertex with in-degree 0 is ready.

  1. Count every vertex's in-degree.
  2. Put every vertex with in-degree 0 in a queue.
  3. Take the vertex u at the front, and add it to the order.
  4. For each arrow u → v, lower v's in-degree by 1. If it reaches 0, add v at the back of the queue.
  5. Go back to step 3 until the queue is empty.

Step 4 is passing a course. Every course that needed u now waits for one fewer.

In the steps, the number above each vertex is its in-degree. Filled vertices are in the order, the purple one is being taken, and bold arrows are being taken away. The queue keeps every vertex that joined it: crossed boxes have been taken, and orange ones just joined.

Kahn's algorithm on the six courses
021120324051
20412345
Start: 2 and 4 have in-degree 0

The same run as a table:

TakenIn-degrees loweredQueue afterOrder so far
20: 2 → 142
41: 1 → 0, 0: 1 → 01, 02, 4
13: 2 → 102, 4, 1
03: 1 → 032, 4, 1, 0
35: 1 → 052, 4, 1, 0, 3
5noneempty2, 4, 1, 0, 3, 5

The crossed boxes, read left to right, are the order: 2, 4, 1, 0, 3, 5. This order is always valid. A vertex joins the queue only when its in-degree reaches 0. By then, every vertex with an arrow into it has been taken, so all of them are earlier in the order.

3 When the queue runs dry: a cycle

Now add the arrow 5 → 1, which closes the cycle 1 → 3 → 5 → 1. Kahn's algorithm takes 2, 4 and 0, and then the queue is empty:

001120314051
Ringed: stuck at in-degree 1 for good

Course 1 waits for 5, 5 waits for 3, and 3 waits for 1. Each one waits for the one before it, so none of them reaches 0. The order holds only 3 of the 6 vertices.

That is the test: if fewer than V vertices come out, the graph has a cycle. A cycle always stops the queue like this. And a stuck queue always means a cycle. Every vertex left still has an arrow coming in from another vertex left, since arrows from taken vertices are already counted off. Walking those arrows backwards never ends. There are only V vertices, so the walk comes back to one it has seen, and that is a cycle.

So Kahn's algorithm does two jobs in one pass. Course Schedule asks only whether every course can be finished: whether all n vertices come out.

4 Kahn's algorithm in code

The code follows the five steps. Each edge [u, v] is an arrow u → v. It returns the order, or an empty list when a cycle stops it.

It returns 2, 4, 1, 0, 3, 5 on our courses, and an empty list once the arrow 5 → 1 is added.

C++

front, then pop. pop() removes the front but returns nothing, so we read the vertex with front() first. The (int) turns the unsigned size() into an int before it is compared with n.

An int[] filled as we go. taken counts the vertices out, and doubles as the next free place in order. A cycle leaves taken below n.

deque, not a list. popleft() takes from the front in O(1). A list's pop(0) shifts every value left, so it is O(n).

An array with a front index. shift() moves every value, so it is O(n). Reading ready[front] and adding 1 to front is O(1).

A slice as the queue. ready[1:] drops the front without copying anything, so each take is O(1).

usize inside, i32 outside. The vertices are usize so they can index adj and in_degree, and turn back into i32 as they go into order.

Make each list. new List<int>[n] is an array of n nulls, so the loop gives each vertex its own list before the first Add.

Cost. Building adj and the in-degrees reads each edge once. After that, each vertex joins the queue once, and each arrow lowers one in-degree once. So Kahn's algorithm is O(V + E), a few hundred thousand steps at V = 10⁵ and E = 2 × 10⁵. adj takes O(V + E) space, and the queue and the in-degrees take O(V).

5 DFS order: write the plan from the back

DFS gives an order too, with the three colours from the cycle-detection lesson. The moment that matters is when a vertex finishes: its call returns, and it turns black.

When v finishes, everything it points to has finished. Take any arrow v → w:

  • w was white. The search went into w, and w finished before v's call went on.
  • w was black. It finished earlier.
  • w was grey. That is a cycle, so in a DAG it never happens.

So every course that needs v finishes before v does. The finish list is the plan written from the back: a course goes on only after every course that needs it is already on. Reversed, it is a topological order.

Here is DFS on our courses. It starts from 0, and then from every vertex still white, in order. The boxes hold the vertices in the order they finish.

Finish order on the six courses
0grey​1white2white3grey​4white5grey​
Filled and bold: the current path
012345
dfs(0) goes 0 → 3 → 5. All turn grey

The finish list is 5, 3, 0, 1, 2, 4. Reversed, it is 4, 2, 1, 0, 3, 5, a third valid plan. The code is the three-colour cycle check with one line more, where a vertex turns black:

dfs(v):
    state[v] = grey
    for each arrow v → w:
        if state[w] is grey: there is a cycle, stop
        if state[w] is white: dfs(w)
    state[v] = black
    add v to finished

for each vertex v, in order:
    if state[v] is white: dfs(v)
order = finished, reversed

It also costs O(V + E). On a chain of 10⁵ courses, though, its recursion goes 10⁵ calls deep and can overflow the call stack, a Runtime Error.

6 Prerequisite pairs, terms and the smallest order

Which way the arrow points. Course Schedule gives prerequisites[i] = [a, b]: to take a, we must first take b. So b comes first, and the arrow is b → a, the reverse of how the pair reads. Our arrow 4 → 1 arrives as [1, 4]:

for each pair [a, b] in prerequisites:
    adj[b].add(a)
    inDegree[a] += 1

Reading the pair as a → b turns every arrow round. The cycle check still works, since a cycle turned round is still a cycle, but the order comes out backwards.

The fewest terms. A course's term is one more than the latest term among its prerequisites. So we walk along a topological order, and each arrow u → v sets term[v] to at least term[u] + 1. Every prerequisite comes earlier, so a course's term is final when we reach it. Course 5 lands in term 4, after the chain 2, 0, 3, 5. This is the longest path in a DAG, and with weights on the arrows, the same walk finds the longest or shortest path.

The smallest order first. When a problem wants the order that is smallest read left to right, the queue becomes a min-heap. It hands out the smallest ready vertex, so our courses come out 2, 4, 0, 1, 3, 5. Each take costs O(log V), so the run is O(V log V + E).

7 Mistakes

  • Arrows the wrong way. With every prerequisite pair read as a → b, our courses come out 5, 3, 1, 0, 4, 2. Course 5 comes first, though it needs 3.
  • Not reversing the finish list. The DFS finish list 5, 3, 0, 1, 2, 4 starts with 5, the last course of all.
  • Not checking for the cycle. With 5 → 1 added, the queue empties after 2, 4, 0. Course Schedule II wants an empty list there, and returning those three gets Wrong Answer.
  • Only one start in the queue. With only 2 in the queue, 4 is never taken, so 1 and 0 never reach in-degree 0. The run stops after one course and reports a cycle that is not there.
  • In-degrees on an undirected graph. A two-way road counts at both ends, so on the path 0 – 1 – 2 the in-degrees are 1, 2 and 1. The queue starts empty, and Kahn's algorithm reports a cycle. A topological order needs one-way arrows.

8 Which to use, and when

  • Kahn's algorithm, by default. It has no recursion, its cycle check is one count, and a min-heap turns it into the smallest order.
  • DFS order when the code already runs a DFS. The three-colour cycle check gets the order from one extra line.

The sign: some tasks must come before others, and we need a valid order or proof that none exists. Look for "prerequisite", "depends on" or "must come before":

  • Course Schedule asks only whether an order exists: the cycle check. Course Schedule II asks for the order itself.
  • Alien Dictionary hides the arrows in a sorted list of words. Once they are found, it is this lesson.
  • Minimum Height Trees is undirected, but it peels a tree from its leaves inwards, the way Kahn's algorithm peels vertices with in-degree 0.

The next lesson, union-find, groups vertices as edges arrive, one edge at a time.

Before building the graph, say one arrow out loud: "b comes before a, so the arrow is b → a." Most wrong orders start with an arrow drawn the wrong way.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.