Skip to content
IT glossary
AlgorithmsUpdated December 3, 2026

Topological sort

Топологическая сортировка

This is a way to put tasks in a list so that every prerequisite comes before the task that needs it. If the dependencies form a loop, no such ordering exists.

What it means

A topological sort lists every vertex of a directed graph exactly once. For each edge u → v, u must appear before v. Think of the arrow as “must happen before.” Unlike sorting numbers, this does not involve comparing every pair of items: the constraints may leave several valid orders. An order exists exactly when the graph is a directed acyclic graph (DAG). A directed cycle would force some vertex to come before itself.

How to find an order

Kahn’s algorithm keeps track of what is ready. First, count each vertex’s incoming edges (its in-degree) and put all vertices with in-degree zero in a queue. Take a vertex from the queue, append it to the result, and decrement the in-degree of each vertex reached by one of its outgoing edges, once per edge. When a count reaches zero, enqueue that vertex: all its prerequisites have been listed. If the queue runs dry before the result contains every vertex, the graph has a cycle. Otherwise, the remaining graph would have a vertex with no incoming edges from other remaining vertices.

Depth-first search (DFS) offers another approach. Append each vertex when its visit finishes, then reverse the list. To reject cycles, distinguish a vertex that is still on the active DFS path from one whose visit has finished. An edge back to a vertex on the active path reveals a cycle; an edge to a finished vertex does not.

With adjacency lists, both methods take O(V + E) time and O(V) extra space beyond the graph, where V is the number of vertices and E the number of edges.

Example: a build pipeline

compile → test
compile → package
test    → publish
package → publish

Initially, only compile is ready. Once it is listed, either test or package can come next. publish must wait for both. A build runner can use these same dependency counts to start tests and packaging in parallel when resources allow. A topological order itself only gives a valid sequence; it does not specify start times or minimize the total build time. Package installers and data pipeline schedulers use the same dependency model.

In coding interviews

A common prompt asks whether all courses can be completed, or asks for one valid course order. If a pair says “course B requires course A,” build the edge A → B, and include courses with no prerequisites or dependents. Check the result by confirming that it contains every course once and that every edge points from an earlier position to a later one. If the interviewer asks whether the order is unique, watch the ready queue in Kahn’s algorithm: on a DAG, having two or more ready vertices at any step means there is more than one valid answer.