M25 · Topological Sort

Topological Sort with Kahn’s Algorithm and Cycle Detection

A topological order lists the nodes of a directed graph so that every edge points forward. Kahn’s algorithm builds one by repeatedly taking a node nothing else is waiting on. If it runs out of such nodes before the graph is empty, the leftovers prove there is a cycle, and no order exists.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M25 Topological Sort · 1 of 1 lessons available

You will be able to

  • Define a topological order and explain why it exists exactly when a directed graph has no cycle.
  • Run Kahn’s algorithm by hand: count in-degrees, queue the sources, remove edges and enqueue nodes whose in-degree reaches 0.
  • Explain why every output order is valid and why left-over nodes mean a cycle, and find a concrete cycle among them.
  • Derive O(V + E) time and space and identify where each term comes from.
  • Choose a tie-break (FIFO, ascending, smallest-first with a heap) and compare Kahn’s algorithm with DFS finish order.

Helpful before this lesson

  • M24 BFS and DFS — Breadth-first and depth-first search on graphs and grids, and what each one finds.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Build steps, course prerequisites, spreadsheet formulas, package dependencies: all are tasks with "must happen before" constraints. Draw each task as a node and each constraint "a before b" as an edge a → b. A topological order is a list of all nodes in which every edge points forward: for every edge a → b, a comes earlier than b.

Such an order exists exactly when the graph has no directed cycle (a DAG, directed acyclic graph). If a → b → c → a, then a must precede itself: impossible. Conversely, every DAG has at least one node with no incoming edge (otherwise you could walk backwards forever, and with finitely many nodes you would repeat one: a cycle), and that observation is the whole algorithm.

The number of incoming edges of a node is its in-degree. A node with in-degree 0, a source, waits for nothing, so it can go first. Remove it and its outgoing edges, and the rest of the graph is still a DAG with new sources. Repeat until nothing is left.

Kahn’s algorithm

kahn(n, edges):
    indegree = [0] * n
    for (u, v) in edges: adj[u].append(v); indegree[v] += 1
    queue = [v for v in 0..n-1 if indegree[v] == 0]     # ascending
    order = []
    while queue not empty:
        u = queue.dequeue()
        order.append(u)
        for v in adj[u]:                                 # ascending
            indegree[v] -= 1                             # "remove" edge u → v
            if indegree[v] == 0: queue.enqueue(v)
    return order, len(order) < n                         # True = cycle

Nothing is deleted from the graph. "Removing" an edge just decrements the in-degree of its target, so indegree[v] always means "incoming edges from nodes not yet output". The lab shows that number as each node's tag, draws removed edges dashed, and keeps the queue and the order built so far as two rows in front of the graph. Step through the Course plan preset: 4 and 5 start with in-degree 0, so they go first; outputting 5 frees 0 and 2, and so on, giving 4 5 0 2 3 1.

Why the output is valid. A node is enqueued only when its in-degree is 0, that is, after every node with an edge into it has been output. So for every edge u → v, u is output before v is even enqueued.

Why leftovers mean a cycle. Suppose the queue empties with some nodes never output. Each of them still has in-degree > 0, and its remaining incoming edges come from other nodes that were never output (output nodes have had their edges removed). So from any leftover node you can step backwards along an edge to another leftover node, forever. With finitely many nodes, that backward walk repeats a node, and the repeated stretch is a directed cycle. The lab does exactly that walk at the end of the Cycle: no order preset and names the cycle 1 → 2 → 3 → 1.

Not every leftover node lies on a cycle. In that preset, node 4 only depends on 3, but 3 is stuck, so 4 is stuck behind it. Kahn's algorithm reports "no order"; finding which nodes form cycles (strongly connected components) is a separate, also linear-time, problem.

Ties: which order do you get?

Most DAGs have many topological orders. In Build steps, nodes 0 and 1 are both sources, and either could come first. Which one Kahn's algorithm outputs depends only on how the waiting nodes are picked:

  • FIFO queue, sources and successors in ascending order (this lesson and its code): reproducible, roughly "level by level".
  • Stack instead of queue: also valid, a different order, tends to finish one chain before starting another.
  • Min-heap: always output the smallest available node. The result is the lexicographically smallest topological order, at O((V + E) log V) instead of O(V + E). Use this when a problem asks for "the smallest" valid order.

All three are correct. Do not compare an order against a single expected answer unless the tie-break is specified; compare against the definition (every edge points forward) instead, which is what the randomized tests here do.

Cost: O(V + E)

Phase Work
Build adjacency lists and count in-degrees one step per edge: O(E), plus O(V) to allocate
Queue the sources one check per node: O(V)
Main loop each node is dequeued at most once (O(V)); each edge is "removed" once, when its source is output (O(E))

Total O(V + E) time and O(V + E) space for the lists, in-degrees and queue. The Edge steps metric in the lab counts every edge twice for an acyclic graph: once while counting, once while removing. In the cycle case, edges out of stuck nodes are counted but never removed. (This implementation sorts each adjacency list to fix the neighbour order, which adds an O(E log E) term in the worst case; with input already in order, or without the determinism requirement, it is not needed.)

Kahn’s algorithm or DFS?

The other classic method runs DFS over all nodes and outputs nodes in reverse finish order: a node finishes only after everything it points to has finished, so reversing puts it before them. A back edge to a gray node during that DFS signals a cycle (see the BFS and DFS lesson).

Kahn DFS finish order
Time O(V + E) O(V + E)
Cycle detection leftovers after the queue empties a back edge
Recursion none depth up to V (or an explicit stack)
Natural extras process "levels" or parallel batches; easy smallest-first variant with a heap fits naturally into other DFS-based algorithms (e.g. strongly connected components)

Kahn's algorithm is the usual choice for schedulers and build tools because it is iterative and exposes, at every moment, the set of tasks that are ready to run.

Built-in support

  • Python: graphlib.TopologicalSorter (standard library since 3.9). static_order() yields a topological order and raises CycleError (with a cycle in its arguments) if there is none; prepare(), get_ready() and done() expose the ready set for parallel processing, the same idea as Kahn's queue. The Python tests here check their cycle verdict against it.
  • C#, Java, C++: no topological sort in the standard library. Build it from Queue<int> / ArrayDeque<Integer> / std::queue<int>, or from PriorityQueue / std::priority_queue for the smallest-first variant. (Java's PriorityQueue and C#'s PriorityQueue<TElement, TPriority> are min-heaps by default; C++'s std::priority_queue is a max-heap unless you pass std::greater<>.)

The teaching implementation

Kahn/kahn takes the node count and the edge list, sorts each adjacency list, and returns the nodes output in order together with a HasCycle flag (order.Count < n). Returning the partial order instead of throwing keeps the cycle case inspectable: the nodes missing from it are exactly the stuck ones.

All four languages run one shared fixture with exact expected orders (chains, a diamond, the course plan, ties, a graph with no edges, a single node, and three kinds of cycle: the whole graph, a cycle after a valid prefix, and a separate cycle next to a valid part). They also run 600 random graphs, about a third of them allowed to contain cycles: the cycle verdict is compared with brute-force source removal, and every returned order is checked edge by edge.

Common mistakes

  • Counting out-degrees instead of in-degrees, or decrementing the source instead of the target.
  • Enqueueing a node more than once by checking indegree[v] <= 0 or by re-scanning all nodes each round (which also makes the algorithm O(V²)).
  • Forgetting the cycle check. Without comparing order.length with n, a cyclic graph silently yields a partial order that looks like an answer.
  • Treating the order as unique and testing against one expected list.
  • Edges in the wrong direction. "a depends on b" means b → a; decide once and say it out loud.

Edge cases

  • No edges: every node is a source; with ascending seeding the order is 0, 1, …, n − 1.
  • A single node: the order is that node.
  • No sources at all: the queue starts empty, nothing is output, and every node is left over (three-cycle in the fixture).
  • Two separate parts, one cyclic: the acyclic part is output, the cyclic part is left over.
  • Opposite edges a → b and b → a: a cycle of length 2.

Worked practice

1. Edges 0 → 2, 1 → 2, 2 → 3, 1 → 3. Run Kahn's algorithm with ascending tie-breaks.

Answer

In-degrees: 0:0, 1:0, 2:2, 3:2. Queue 0, 1. Output 0 (2 drops to 1). Output 1 (2 drops to 0 and is enqueued; 3 drops to 1). Output 2 (3 drops to 0, enqueued). Output 3. Order: 0 1 2 3.

2. Add the edge 3 → 1 to that graph. What happens?

Answer

Now 1 has in-degree 1, so only 0 is a source. Output 0 (2 drops to 1). The queue is empty with 1, 2 and 3 left over (in-degrees 1, 1 and 2). Walking backwards from 1: 3 → 1, then 2 → 3, then 1 → 2, so 1 → 2 → 3 → 1 is a cycle (and so is 1 → 3 → 1). No topological order exists.

3. How many topological orders does a graph with n nodes and no edges have, and which one does this implementation return?

Answer

n!, since any permutation is valid. This implementation queues the sources in ascending order, so it returns 0, 1, …, n − 1.

4. You must schedule build steps on 4 machines, running every step as soon as its dependencies finish. How does Kahn's algorithm help?

Answer

The queue is the set of steps whose dependencies are all done. Take up to 4 steps from it, run them, and when each finishes, decrement its successors' in-degrees and enqueue any that reach 0. That is Kahn's algorithm with the dequeues spread over time, exactly what graphlib's get_ready() and done() provide.

Summary

  • A topological order puts every edge u → v with u before v; it exists iff the graph is a DAG.
  • Kahn's algorithm outputs nodes whose in-degree has dropped to 0 and decrements their successors.
  • If fewer than n nodes come out, the leftovers contain a cycle; walking backwards among them finds one.
  • O(V + E) time and space. The tie-break (queue, stack, min-heap) picks one of many valid orders.
  • DFS reverse finish order is the main alternative; Python ships graphlib.TopologicalSorter.

Full implementation

Kahn's algorithm in four languages, each checked against one shared fixture of exact output orders and left-over nodes (chains, ties, no edges, three kinds of cycle) and 600 random graphs whose cycle verdict is compared with brute-force source removal and whose orders are checked edge by edge (Python also against graphlib).

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>The nodes output in order, and whether some were left over (then a cycle exists).</summary>
public sealed record TopoResult(List<int> Order, bool HasCycle);
 
/// <summary>
/// Kahn's algorithm. An edge (u, v) means u must come before v. Sources are
/// queued in ascending order and successors are processed in ascending order
/// (FIFO queue), so the result is deterministic. O(V + E) time and space.
/// </summary>
public static class TopologicalSort
{
    public static TopoResult Kahn(int nodeCount, IReadOnlyList<(int From, int To)> edges)
    {
        var adj = new List<int>[nodeCount];
        for (int i = 0; i < nodeCount; i++)
            adj[i] = [];
        var indegree = new int[nodeCount];
        foreach (var (u, v) in edges)
        {
            adj[u].Add(v);
            indegree[v]++;
        }
        foreach (var list in adj)
            list.Sort();
        var queue = new Queue<int>();
        for (int v = 0; v < nodeCount; v++)
            if (indegree[v] == 0)
                queue.Enqueue(v);
        var order = new List<int>(nodeCount);
        while (queue.Count > 0)
        {
            int u = queue.Dequeue();
            order.Add(u);
            foreach (int v in adj[u])
            {
                indegree[v]--;
                if (indegree[v] == 0)
                    queue.Enqueue(v);
            }
        }
        return new TopoResult(order, order.Count < nodeCount);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/TopologicalSort.cs

"""Kahn's topological sort.
 
An edge (u, v) means u must come before v. Sources are queued in ascending order
and successors are processed in ascending order (FIFO queue), so the result is
deterministic. O(V + E) time and space. graphlib.TopologicalSorter in the
standard library does the same job and raises CycleError on a cycle.
"""
 
from __future__ import annotations
 
from collections import deque
from collections.abc import Sequence
 
 
def kahn(node_count: int, edges: Sequence[tuple[int, int]]) -> tuple[list[int], bool]:
    """The nodes output in order, and whether some were left over (then a cycle exists)."""
    adj: list[list[int]] = [[] for _ in range(node_count)]
    indegree = [0] * node_count
    for u, v in edges:
        adj[u].append(v)
        indegree[v] += 1
    for successors in adj:
        successors.sort()
    queue: deque[int] = deque()
    for v in range(node_count):
        if indegree[v] == 0:
            queue.append(v)
    order: list[int] = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                queue.append(v)
    return order, len(order) < node_count

Tested on CPython 3.14.0 · examples/python/dsa_examples/topological_sort.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
 
/**
 * Kahn's algorithm. An edge {u, v} means u must come before v. Sources are
 * queued in ascending order and successors are processed in ascending order
 * (FIFO queue), so the result is deterministic. O(V + E) time and space.
 */
public final class TopologicalSort {
    private TopologicalSort() {
    }
 
    /** The nodes output in order, and whether some were left over (then a cycle exists). */
    public record Result(List<Integer> order, boolean hasCycle) {
    }
 
    public static Result kahn(int nodeCount, int[][] edges) {
        List<List<Integer>> adj = new ArrayList<>(nodeCount);
        for (int i = 0; i < nodeCount; i++) {
            adj.add(new ArrayList<>());
        }
        int[] indegree = new int[nodeCount];
        for (int[] e : edges) {
            adj.get(e[0]).add(e[1]);
            indegree[e[1]]++;
        }
        for (List<Integer> list : adj) {
            Collections.sort(list);
        }
        Queue<Integer> queue = new ArrayDeque<>();
        for (int v = 0; v < nodeCount; v++) {
            if (indegree[v] == 0) {
                queue.add(v);
            }
        }
        List<Integer> order = new ArrayList<>(nodeCount);
        while (!queue.isEmpty()) {
            int u = queue.remove();
            order.add(u);
            for (int v : adj.get(u)) {
                indegree[v]--;
                if (indegree[v] == 0) {
                    queue.add(v);
                }
            }
        }
        return new Result(order, order.size() < nodeCount);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/TopologicalSort.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <queue>
#include <utility>
#include <vector>
 
// Kahn's algorithm. An edge {u, v} means u must come before v. Sources are
// queued in ascending order and successors are processed in ascending order
// (FIFO queue), so the result is deterministic. O(V + E) time and space.
namespace bekadan::dsa::topological {
 
// The nodes output in order, and whether some were left over (then a cycle exists).
struct Result {
    std::vector<int> order;
    bool has_cycle;
};
 
inline Result kahn(int node_count, const std::vector<std::pair<int, int>>& edges) {
    const auto n = static_cast<std::size_t>(node_count);
    std::vector<std::vector<int>> adj(n);
    std::vector<int> indegree(n, 0);
    for (const auto& [u, v] : edges) {
        adj[u].push_back(v);
        ++indegree[v];
    }
    for (auto& list : adj) std::ranges::sort(list);
    std::queue<int> queue;
    for (int v = 0; v < node_count; ++v)
        if (indegree[v] == 0)
            queue.push(v);
    std::vector<int> order;
    order.reserve(n);
    while (!queue.empty()) {
        const int u = queue.front();
        queue.pop();
        order.push_back(u);
        for (const int v : adj[u]) {
            --indegree[v];
            if (indegree[v] == 0)
                queue.push(v);
        }
    }
    const bool has_cycle = order.size() < n;
    return {std::move(order), has_cycle};
}
 
}  // namespace bekadan::dsa::topological

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/topological_sort.hpp

References