Updated 1 day ago | GitHub
On this page

Topological Sort

Introduction

Aside from DFS and BFS, the most common graph concept that interviews will test is topological sorting. Topological sorting produces a linear ordering of nodes in a directed graph such that the direction of edges is respected.

A topological sort is an ordering of nodes for a directed acyclic graph (DAG) such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.

Example

An application of this algorithm is ordering a sequence of tasks given their dependencies on other tasks. In this application, there is a directed edge from u to v if task u must be completed before task v can start. For example, when cooking, we need to turn on the oven (task u) before we can bake the cookies (task v).

Implementation:

A common way to compute a topological sort is a modification of DFS. (Kahn’s algorithm, which repeatedly takes a node with no remaining incoming edges, is another.) The DFS version runs DFS on the entire graph and adds each node to the front of the global ordering of nodes, but only after all of the node’s children have been visited. A node is therefore prepended only after everything reachable from it is already in the ordering, so it lands ahead of all of its descendants. This ensures that parent nodes will be ordered before their child nodes, and honors the forward direction of edges in the ordering. The code below prepends with deque.appendleft; appending each finished node to the end instead would produce the reverse of a valid ordering.

Graph with no cycles

from collections import deque

def top_sort(graph):
    sorted_nodes, visited = deque(), set()
    for node in graph.keys():
        if node not in visited:
           dfs(graph, node, visited, sorted_nodes)
    return list(sorted_nodes)
 
def dfs(graph, start_node, visited, sorted_nodes):
    visited.add(start_node)
    if start_node in graph:
        neighbors = graph[start_node]
        for neighbor in neighbors:
            if neighbor not in visited:
                dfs(graph, neighbor, visited, sorted_nodes)
    sorted_nodes.appendleft(start_node)

This version assumes the graph is a DAG. A topological ordering exists only when the graph has no directed cycles, and the code above does not check for one: on a graph with a cycle it still returns a list, but at least one edge on the cycle points backward in that list. To detect a cycle, also track the nodes on the current DFS path and stop when the DFS reaches one of them again.