← Back to Algorithms, page 4

algorithms-0068 · Medium mid

Topological sort: order the tasks of a dependency graph so every prerequisite comes first, and report when a cycle makes that impossible.

Kahn's algorithm counts in-degrees, starts a queue with every node of in-degree 0, and repeatedly removes a node and decrements its neighbours, enqueuing any that reach 0. If fewer than V nodes come out, there is a cycle. The DFS method outputs nodes in reverse post-order and detects cycles with a grey (in-progress) colour. Both are O(V + E).

Full answer

Problem

Given n tasks 0..n-1 and edges (u, v) meaning u must be done before v, return an order containing every task that respects all edges, or [] if no such order exists.

Example: edges [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)] with n = 6 has valid orders such as [4, 5, 2, 0, 3, 1]. Edges [(0, 1), (1, 2), (2, 0)] form a cycle, so the answer is [].

Constraints: up to 10^5 nodes and edges.

Brute force

Try all n! permutations and check each against every edge: O(n! * E). Only usable for tiny graphs (the tests use it up to 6 nodes as a reference).

Optimal approach

Kahn's algorithm (BFS):

  1. Build adjacency lists and in-degree counts.
  2. Queue every node with in-degree 0.
  3. Pop u, append to the order, and decrement the in-degree of each neighbour; enqueue those reaching 0.
  4. If the order has n nodes, return it; otherwise there is a cycle.

DFS alternative: colour nodes white, grey (on the current path), black (done). Append a node when it turns black; reverse at the end. Meeting a grey node means a back edge, which means a cycle.

Why it works

A node with in-degree 0 has no unfinished prerequisites, so it is safe to place next; removing it cannot create new constraints. In a DAG some node always has in-degree 0, so Kahn's algorithm only stops early when every remaining node lies on or behind a cycle. In the DFS version, a node finishes only after everything reachable from it has finished, so reverse finishing order puts each node before its descendants.

Complexity

O(V + E) time and space for both methods.

Code

python
import random
from collections import deque
from itertools import permutations


def topo_kahn(n, edges):
    """Kahn's algorithm. Returns an order, or [] if the graph has a cycle. O(V + E)."""
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:                   # u must come before v
        adj[u].append(v)
        indeg[v] += 1
    q = deque(u for u in range(n) if indeg[u] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []


def topo_dfs(n, edges):
    """DFS with three colours; reverse post-order is a topological order."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color, out = [WHITE] * n, []
    for s in range(n):
        if color[s] != WHITE:
            continue
        stack = [(s, iter(adj[s]))]
        color[s] = GREY
        while stack:
            u, it = stack[-1]
            nxt = next(it, None)
            if nxt is None:
                color[u] = BLACK
                out.append(u)
                stack.pop()
            elif color[nxt] == GREY:
                return []                # back edge: cycle
            elif color[nxt] == WHITE:
                color[nxt] = GREY
                stack.append((nxt, iter(adj[nxt])))
    return out[::-1]


def is_valid_order(n, edges, order):
    pos = {u: i for i, u in enumerate(order)}
    return len(order) == n and all(pos[u] < pos[v] for u, v in edges)


def brute_has_order(n, edges):
    return any(is_valid_order(n, edges, p) for p in permutations(range(n)))


if __name__ == "__main__":
    edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
    for f in (topo_kahn, topo_dfs):
        assert is_valid_order(6, edges, f(6, edges))
        assert f(3, [(0, 1), (1, 2), (2, 0)]) == []
        assert f(1, [(0, 0)]) == []                     # self loop is a cycle
        assert f(3, []) != []
    rng = random.Random(68)
    for _ in range(400):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 8))]
        possible = brute_has_order(n, es)
        for f in (topo_kahn, topo_dfs):
            got = f(n, es)
            assert (got != []) == possible
            if got:
                assert is_valid_order(n, es, got)
    print("all tests passed")

Save as b68_topo_sort.py and run python3 b68_topo_sort.py. It prints all tests passed (Python 3.13.5).

Edge cases

No edges (any order). Self-loop (a cycle). Several components. Duplicate edges (in-degree counts each, which is still consistent). Very deep chains: the DFS code here uses an explicit stack of iterators, so no recursion limit.

Pattern

Dependency ordering on a DAG. It solves course schedule, build systems, spreadsheet recalculation, package installation order, and is the first step for DP on DAGs (longest path, counting paths). Using a min-heap instead of a queue in Kahn's algorithm gives the lexicographically smallest order.

python
import random
from collections import deque
from itertools import permutations


def topo_kahn(n, edges):
    """Kahn's algorithm. Returns an order, or [] if the graph has a cycle. O(V + E)."""
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:                   # u must come before v
        adj[u].append(v)
        indeg[v] += 1
    q = deque(u for u in range(n) if indeg[u] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []


def topo_dfs(n, edges):
    """DFS with three colours; reverse post-order is a topological order."""
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
    WHITE, GREY, BLACK = 0, 1, 2
    color, out = [WHITE] * n, []
    for s in range(n):
        if color[s] != WHITE:
            continue
        stack = [(s, iter(adj[s]))]
        color[s] = GREY
        while stack:
            u, it = stack[-1]
            nxt = next(it, None)
            if nxt is None:
                color[u] = BLACK
                out.append(u)
                stack.pop()
            elif color[nxt] == GREY:
                return []                # back edge: cycle
            elif color[nxt] == WHITE:
                color[nxt] = GREY
                stack.append((nxt, iter(adj[nxt])))
    return out[::-1]


def is_valid_order(n, edges, order):
    pos = {u: i for i, u in enumerate(order)}
    return len(order) == n and all(pos[u] < pos[v] for u, v in edges)


def brute_has_order(n, edges):
    return any(is_valid_order(n, edges, p) for p in permutations(range(n)))


if __name__ == "__main__":
    edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
    for f in (topo_kahn, topo_dfs):
        assert is_valid_order(6, edges, f(6, edges))
        assert f(3, [(0, 1), (1, 2), (2, 0)]) == []
        assert f(1, [(0, 0)]) == []                     # self loop is a cycle
        assert f(3, []) != []
    rng = random.Random(68)
    for _ in range(400):
        n = rng.randint(1, 6)
        es = [(rng.randrange(n), rng.randrange(n)) for _ in range(rng.randint(0, 8))]
        possible = brute_has_order(n, es)
        for f in (topo_kahn, topo_dfs):
            got = f(n, es)
            assert (got != []) == possible
            if got:
                assert is_valid_order(n, es, got)
    print("all tests passed")

Kahn's algorithm and an iterative three-colour DFS; random small graphs are checked against exhaustive permutation search.

Complexity

Time: O(V + E). Space: O(V + E). A heap in place of the queue gives the smallest lexicographic order at O((V + E) log V).

By level

Fresher: Explains prerequisites with in-degrees and runs Kahn's algorithm on a small example. Detects a cycle when nodes remain.

Mid: Implements both Kahn and DFS methods with cycle detection and explains why each is correct. Adapts the queue to compute parallel rounds.

Senior: Discusses incremental topological order when edges are added, build systems that recompute only affected nodes, and very large dependency graphs. Explains DP on DAGs built on the topological order.

Key points

  • Start from in-degree 0 nodes
  • Fewer than V output nodes means a cycle
  • DFS: reverse post-order
  • Grey node on the path means a back edge
  • Both O(V + E)

Common mistakes

  • Reversing edge direction by mistake
  • Forgetting the cycle check at the end
  • Treating black (finished) nodes as cycle evidence in DFS
  • Recursion depth on long chains

Follow-ups

  • How do you get the lexicographically smallest order?
  • How would you schedule tasks in parallel rounds and find the minimum number of rounds?
  • How do you find the longest path in a DAG?

Tips

  • Confirm the edge direction
  • Explain why in-degree 0 is safe
  • Mention the cycle signal for both methods

Evaluation rubric

  • Correct order
  • Detects cycles
  • Correct complexity
  • Knows both methods