Topological Sort

Get to know the topological sort problem and its solution using depth-first search.

Topological ordering and postordering in directed graphs

A topological ordering of a directed graph GG is a total order (The symbol represents a partial order or a strict order relation between elements.) on the vertices such that uvu ≺ v for every edge uvu\rightarrow v. Less formally, a topological ordering arranges the vertices along a horizontal line so that all edges point from left to right. A topological ordering is clearly impossible if graph GG has a directed cycle—the rightmost vertex of the cycle would have an edge pointing to the left!

On the other hand, consider an arbitrary postordering of an arbitrary directed graph GG. Our earlier analysis implies that u.post<v.postu.post < v.post for any edge uvu\rightarrow v, and GG contains a directed path from vv to uu, therefore also containing a directed cycle through uvu\rightarrow v. Equivalently, if GG is acyclic, then u.post>v.postu.post > v.post for every edge uvu\rightarrow v. It follows that every directed acyclic graph GG has a topological ordering; in particular, the reversal of any postordering of GG is a topological ordering of GG.

Press + to interact
Reversed post ordering of the dag from the previous lesson
Reversed post ordering of the dag from the previous lesson

If we require the topological ordering in a separate data structure, we can simply write the vertices into an array in reverse postorder in O(V+E)O(V + E) time, as shown in the algorithm below.

Implicit topological sort

But recording the topological order into a separate data structure is usually overkill. In most applications of the topological sort, the ordered list of the vertices is not our actual goal; rather, we want to perform some fixed computation at each vertex of the graph, either in topological order or in reverse topological order. For these applications, it is not necessary to record the topological order at all!

Algorithm


TopologicalSort(G):for all vertices vv.statusNewclockVfor all vertices vif v.status=NewclockTopSortDFS(v,clock)retur ...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy