Topological Sort

Order the vertices of a directed graph so that every edge points forward, or find the cycle that makes it impossible.

A directed graph has n vertices, numbered 0 to n - 1, and its edges come as pairs [a, b], each one an arrow from a to b. List all the vertices in an order where every arrow points forward, so a comes before b. If no such order exists, return an empty list. When several orders work, any one of them is correct.

Example 1
Input: n = 6, edges = [[5, 0], [5, 2], [4, 0], [4, 1], [2, 3], [3, 1]]
Output: [4, 5, 0, 2, 3, 1]
Explanation: every arrow goes from an earlier entry to a later one. [5, 4, 2, 3, 1, 0] is also correct.
Example 2
Input: n = 3, edges = [[0, 1], [1, 2], [2, 0]]
Output: []
Explanation: the arrows go round in a loop, 0 to 1 to 2 and back to 0. Whichever vertex is listed first, the arrow into it points backward.
Solution

The Idea

Picture six jobs on a to-do list, numbered 0 to 5, where some jobs have to wait for others. The arrow 5 → 0 in Example 1 says that job 5 must be finished before job 0 can start. A schedule that respects every arrow is what the problem asks for, and such an order of the vertices is called a topological order. Finding one is a topological sort.

The left half of the picture shows the graph from Example 1. Next to each vertex is its indegree, the number of arrows coming into it. Vertex 0 has two arrows coming in, from 5 and from 4, so its indegree is 2. Vertex 2 has one, from 5. Vertices 4 and 5, drawn in orange, have indegree 0.

Left: the graph with arrows 5 to 0, 5 to 2, 4 to 0, 4 to 1, 2 to 3 and 3 to 1, each vertex labelled with its indegree; 4 and 5 have indegree 0. Right: the same vertices in the order 4, 5, 0, 2, 3, 1, where every arrow points to the right.

So which job can go first? Not 0, because 5 and 4 must come before it. A vertex with indegree 0 waits for nothing, so 4 or 5 can start the list. Say 4 goes first. Its arrows to 0 and 1 are now kept, whatever comes next, so we can cross them off. That drops the indegree of 0 from 2 to 1, and of 1 from 2 to 1.

Next comes 5, the other vertex with indegree 0. Crossing off its arrows drops 0 to indegree 0 and 2 to indegree 0, so both are ready now. Placing 0 crosses off nothing, because no arrow leaves 0. Placing 2 makes 3 ready, and placing 3 makes 1 ready. The list is 4, 5, 0, 2, 3, 1, and in the right half of the picture every arrow of the graph points to the right.

Now try Example 2. Each of its three vertices has one arrow coming in, so no vertex has indegree 0 and nothing can start the list. The vertices wait on each other in a loop, which is called a cycle. A graph with arrows and no cycle is a DAG, short for directed acyclic graph, and every DAG has a topological order.

So the whole method is one move, repeated: take a vertex whose indegree has dropped to 0, list it, and cross off its outgoing arrows. If the moves run out before every vertex is listed, the vertices left over are stuck behind a cycle. This method is known as Kahn's algorithm.

Solution Approach

Kahn's algorithm needs three decisions: how to store the arrows and the indegrees, where to keep the vertices that are ready, and how to notice a cycle. A depth-first version is an optional alternative.

Storing the arrows and the indegrees

Crossing off the arrows that leave a vertex means finding them fast. So the edge pairs become an adjacency list: for each vertex, a list of the vertices its arrows point to. In Example 1, vertex 4 gets the list [0, 1], vertex 5 gets [0, 2], vertex 2 gets [3] and vertex 3 gets [1]. The lists of 0 and 1 stay empty.

The same pass over the edges counts the arrows into each vertex. For Example 1 that gives the indegrees 2, 2, 1, 1, 0, 0 for vertices 0 to 5, the labels in the picture.

Keeping the ready vertices

Where do the vertices with indegree 0 wait until they are listed? Searching all the vertices for one after every step would cost a full scan each time. Instead, a vertex goes into a queue at the moment its indegree reaches 0. Here the queue is an ArrayDeque of vertex numbers, and in Example 1 it starts as [4, 5].

Does a vertex need a mark so that it is not queued twice? No. A vertex enters the queue only when its count drops to exactly 0, and the count only goes down, so each vertex is queued once.

Noticing a cycle

How does the code know that a cycle blocked the order? Vertices on a cycle never reach indegree 0, so they never reach the queue. When the queue runs empty, the list is shorter than n, and that is the sign.

Leaving out this length check is a real trap. Take four vertices with the arrows 0 → 1, 1 → 2, 2 → 1 and 2 → 3. Without the check, the method returns [0], an order that leaves out three vertices. In Example 2 the queue starts empty, so the method without the check also returns [] there, and that example alone would not reveal the bug.

Optional: a depth-first version

Depth-first search (DFS) follows arrows as far as they go before backing up. To get an order from it, push a vertex onto a stack only after every vertex reachable from it is finished. The method below takes the adjacency list adj, an array visited that marks the vertices already entered, and the stack:

Java
static void dfs(int u, List<List<Integer>> adj, boolean[] visited, Deque<Integer> stack) {
    visited[u] = true;
    for (int next : adj.get(u)) {
        if (!visited[next]) {
            dfs(next, adj, visited, stack);
        }
    }
    stack.push(u);   // pushed after every vertex reachable from u
}

Calling dfs for each unvisited vertex from 0 to 5 and reading the stack from the top gives [5, 4, 2, 3, 1, 0] for Example 1, the other order in its explanation. Everything that must come after u is pushed before u, so it sits below u on the stack.

Two traps come with it. Recording each vertex when the search first enters it gives [0, 1, 2, 3, 4, 5], which lists 0 before 5 against the arrow 5 → 0. And on Example 2 this dfs returns [0, 1, 2] instead of reporting the cycle, so it needs a separate check for cycles. Kahn's algorithm gets that check for free from the length of its list.

Java Solution

The method topoSort works in these steps:

  1. First, build the adjacency list adj, one empty list per vertex, and the array indegree. For each pair edge, add edge[1] to the list of edge[0] and add one to indegree[edge[1]].
  2. Create queue, an ArrayDeque, and add every vertex whose indegree is 0.
  3. Create the list order. While the queue is not empty, take the vertex u from its front and append it to order.
  4. For each vertex next in the list of u, lower indegree[next] by one. If it reaches 0, add next to the queue.
  5. When the queue is empty, return order if it holds all n vertices, and an empty list otherwise.

The main method runs both examples and four more graphs: three vertices with no arrows, the four-vertex graph where 1 and 2 wait on each other, a vertex with an arrow to itself, and the chain 3 → 2 → 1 → 0.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class TopologicalSort {

    // Kahn's algorithm. Returns an empty list if the graph has a cycle.
    public static List<Integer> topoSort(int n, int[][] edges) {
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }
        int[] indegree = new int[n];
        for (int[] edge : edges) {
            adj.get(edge[0]).add(edge[1]);     // arrow edge[0] -> edge[1]
            indegree[edge[1]]++;               // one more arrow into edge[1]
        }

        Deque<Integer> queue = new ArrayDeque<>();
        for (int vertex = 0; vertex < n; vertex++) {
            if (indegree[vertex] == 0) {
                queue.add(vertex);             // nothing has to come before it
            }
        }

        List<Integer> order = new ArrayList<>();
        while (!queue.isEmpty()) {
            int u = queue.poll();
            order.add(u);
            for (int next : adj.get(u)) {
                indegree[next]--;              // the arrow u -> next is now kept
                if (indegree[next] == 0) {
                    queue.add(next);           // everything before next is placed
                }
            }
        }
        return order.size() == n ? order : new ArrayList<>();
    }

    public static void main(String[] args) {
        int[][] example1 = {{5, 0}, {5, 2}, {4, 0}, {4, 1}, {2, 3}, {3, 1}};
        int[][] example2 = {{0, 1}, {1, 2}, {2, 0}};
        int[][] noArrows = {};
        int[][] partCycle = {{0, 1}, {1, 2}, {2, 1}, {2, 3}};   // 1 and 2 wait on each other
        int[][] selfLoop = {{1, 1}};                            // 1 waits on itself
        int[][] chain = {{3, 2}, {2, 1}, {1, 0}};
        System.out.println(topoSort(6, example1));
        System.out.println(topoSort(3, example2));
        System.out.println(topoSort(3, noArrows));
        System.out.println(topoSort(4, partCycle));
        System.out.println(topoSort(2, selfLoop));
        System.out.println(topoSort(4, chain));
    }
}

Running it prints:

Output
[4, 5, 0, 2, 3, 1]
[]
[0, 1, 2]
[]
[]
[3, 2, 1, 0]

Example 1 comes out as [4, 5, 0, 2, 3, 1], the same order as the walk through the picture, because the queue hands out 4 before 5 and 0 before 2. Example 2 gives [], since no vertex there has indegree 0. With no arrows at all, every vertex is ready at the start, and the third line lists them in number order, [0, 1, 2].

The fourth and fifth lines are both [], though each graph has a vertex that can go first. In the four-vertex graph only 0 gets listed, and the same happens in the graph where 1 has an arrow to itself, so the length check catches both. The last line, [3, 2, 1, 0], shows that the order follows the arrows, not the vertex numbers.

Complexity

The work is one pass over the edges to build the lists, then one turn for each vertex as it leaves the queue. Here V is the number of vertices (n in the code) and E the number of edges.

  • Time: O(V + E), because each edge is read once to fill adj and indegree, each vertex enters the queue at most once, and each arrow is crossed off once.
  • Space: O(V + E), because the adjacency list stores every edge once, while indegree, the queue and order each hold at most V entries.

For the same idea with courses and the courses they require first, see Course Schedule.