Topological Sort

Order the nodes of a directed acyclic graph so every edge points forward. Kahn's algorithm peels nodes with no incoming edges; DFS reverses its finish order. Both are O(V + E) and both detect cycles.

Overview

What it is

A topological order lines up the nodes of a directed graph so that every edge goes from an earlier node to a later one. If course 5 is a prerequisite for course 2, then 5 comes before 2. Such an order exists exactly when the graph has no directed cycle, so the graph must be a DAG, a directed acyclic graph. Most graphs have several valid orders.

The running example has six courses and six prerequisite edges.

The in-degree of a node is the number of edges coming into it. A node with in-degree 0 has no prerequisites left and can go next. In the example, nodes 4 and 5 have no incoming edges, so their in-degree is 0. Nodes 2 and 3 have one each: 2 waits on 5, and 3 waits on 2. Nodes 0 and 1 have two each: 0 waits on 5 and 4, and 1 waits on 4 and 3.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio