Algorithm · Graphs · O(V + E)

Topological sort

Order the vertices of a directed acyclic graph so every edge points forward. Kahn’s algorithm repeatedly removes vertices with no incoming edges.

The full derivation, edge cases and exercises are in the lesson Topological sort with Kahn’s algorithm and cycle detection. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

A vertex with in-degree zero has no unmet prerequisites, so it can go first. Removing it lowers its neighbours’ in-degrees, which may free them in turn. If vertices remain when no in-degree is zero, they lie on a cycle and no order exists.

Steps

  1. Count each vertex’s in-degree.
  2. Queue every vertex with in-degree 0.
  3. Dequeue a vertex, append it to the order, and decrement its neighbours’ in-degrees, queueing any that reach 0.
  4. If the order has fewer than V vertices, report a cycle.

Invariants

What holds at every step; the correctness argument rests on these.

  • Every vertex in the output appears after all of its predecessors.
  • A vertex is queued exactly when all its incoming edges come from output vertices.

Complexity

Topological sort complexity
CaseTimeExtra space
Whole sortO(V + E)O(V)

When to use it

Use it when

  • Build systems, course prerequisites, task scheduling: anything with “must come before”.
  • Detecting whether a directed graph has a cycle.

Avoid it when

  • The graph is undirected or has cycles you need to keep: no topological order exists.

Step through it

The interactive lab for topological sort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Data structures it uses

Problems, patterns and exercises

References