Graphs · O(V + E)

Topological sort

Kahn's algorithm with in-degrees, a source queue and cycle detection.

The full explanation, derivation and practice are in the lesson Topological sort with Kahn’s algorithm and cycle detection.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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