The canonical application of topological sorting is in scheduling a sequence of jobs or tasks based on their dependencies. The jobs are represented by vertices, and there is an edge from x to y if job x must be completed before job y can be started (for example, when washing clothes, the washing machine must finish before we put the clothes in the dryer). Then, a topological sort gives an order in which to perform the jobs.


  • Scheduling tasks based on dependencies
  • Compilation / Build orders
  • Data serialization
  • Which order to load tables with foreign keys to databases


Kahn’s Algorithm

L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edge
while S is non-empty do
    remove a node n from S
    add n to tail of L
    for each node m with an edge e from n to m do
        remove edge e from the graph
        if m has no other incoming edges then
            insert m into S
if graph has edges then
    return error   (graph has at least one cycle)
    return L   (a topologically sorted order)

Depth-First Search

L ← Empty list that will contain the sorted nodes
while there are unmarked nodes do
    select an unmarked node n
 function visit(node n)
    if n has a permanent mark then return
    if n has a temporary mark then stop   (not a DAG)
    mark n temporarily
    for each node m with an edge from n to m do
    mark n permanently
    add n to head of L


CTCI 4.7 Build Order