Topological sort

In one sentence

Order a directed graph so every edge points forward: repeatedly take a node with no remaining prerequisites (Kahn), or reverse the DFS finish order; nodes left over mean a cycle.

Kahn's algorithm: a node is ready when its last prerequisite is done. If the queue empties early, the remaining nodes are blocked by a cycle.

How it works

  • It exists only for a DAG and is usually not unique: many orders can be valid.
  • Kahn: queue in-degree-0 nodes; pop one, decrement its neighbors, queue those that reach 0.
  • Fewer than V nodes out means a cycle: the leftovers are on it or depend on it.
  • DFS alternative: append each node when it finishes, then reverse; a gray neighbor means a cycle.
  • Both are O(V + E); Kahn's queue shows which tasks can run in parallel.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your release tool runs Kahn's algorithm over 2,000 packages. The queue empties after only 1,940 packages are ordered. What does that tell you?

Go deeper

Solve it in Python 9
Full explanation

A topological order lists a directed graph's nodes so that every edge u → v puts u before v: prerequisites first. It exists only for a DAG (directed acyclic graph) and is usually not unique.

Kahn's algorithm (BFS-style):

  1. Count each node's in-degree (incoming edges).
  2. Queue every node with in-degree 0.
  3. Pop a node, append it to the order, decrement each neighbor's in-degree, and queue the ones that reach 0.
  4. If the order has fewer than V nodes, the rest are on a cycle or depend on one.

DFS order: append each node when its DFS finishes, then reverse the list. Detect cycles with three colors: reaching a gray node (still on the current path) is a back edge.

Both are O(V + E). I default to Kahn: it is iterative, the cycle check is a count, and its queue shows what can run in parallel. Python ships it as graphlib.TopologicalSorter (3.9+).

Code Kahn's algorithm for course schedule, plus graphlib
pythonKahn's algorithm for course schedule, plus graphlib
from collections import deque
from graphlib import TopologicalSorter

def course_order(n, prereqs):
    """prereqs: (course, needs) pairs. Returns an order, or [] on a cycle."""
    adj, indeg = [[] for _ in range(n)], [0] * n
    for course, needs in prereqs:
        adj[needs].append(course)              # edge: needs -> course
        indeg[course] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:                  # its last prerequisite is done
                q.append(v)
    return order if len(order) == n else []    # leftovers: on or behind a cycle

# Standard library (Python 3.9+): node -> its predecessors; raises CycleError
deps = {"app": {"lib", "config"}, "lib": {"config"}}
print(list(TopologicalSorter(deps).static_order()))  # ['config', 'lib', 'app']
Real example

Course schedule: 4 courses; 1 and 2 need 0, and 3 needs both 1 and 2. In-degrees: 0→0, 1→1, 2→1, 3→2. The queue starts with 0. Popping 0 drops 1 and 2 to zero; popping 1 drops 3 to one; popping 2 drops it to zero. Order: [0, 1, 2, 3]. Now add 'course 0 needs 3': no node starts at in-degree 0, the order is empty, so the plan is impossible.

Trade-offs +2 · −2

+ You gain

  • Linear, O(V + E), and detects cycles as a by-product.
  • Kahn's queue gives parallel waves: everything in it is ready at once.

− You pay

  • Only for DAGs: with cycles you must report them or break them first.
  • Many valid orders: tests that expect one exact order fail unless you fix tie-breaking.

Use it when

Anything with 'depends on' or 'must happen before': build and task order, course prerequisites, package installs, spreadsheet recalculation, DAG schedulers, deriving a letter order from a sorted alien dictionary.

Avoid it when

Undirected graphs, or directed graphs where cycles are legitimate (social graphs): use plain Graph traversal: BFS and DFS or strongly connected components instead.

Numbers to know 4
  • Time O(V + E); space O(V) for in-degrees and the queue.
  • Course schedule with n courses and p prerequisite pairs: O(n + p).
  • Longest path: O(V + E) on a DAG via topological order plus DP; NP-hard on general graphs.
  • graphlib.TopologicalSorter: in Python's standard library since 3.9.
Common pitfalls 4
  • Edges backwards: the pair (course, prereq) must become prereq → course, or the order comes out reversed.
  • Dropping nodes with no edges: include every node, not just those that appear in pairs.
  • Directed cycle check with a plain visited set: a diamond (two paths to one node) looks like a cycle. Track 'on current path'.
  • Returning a partial order without checking len(order) == n.
Interview questions 3

Answer out loud first, then reveal.

Kahn or DFS: which do you use and why?Show answer

Kahn by default. It's iterative, so no recursion limit; the cycle check is just 'did every node come out?'; and the queue holds exactly the tasks that are ready together, which maps to a parallel scheduler. DFS order is natural if I'm already writing a DFS, but it needs three colors for cycles and a reverse at the end. Both are O(V + E).

How do you recognize it, and what are the variants?Show answer

Signals: prerequisites, dependencies, 'must happen before', build order, or an order hidden in constraints. Variants: return any valid order; report impossibility when there's a cycle; the lexicographically smallest order, by swapping the queue for a min-heap; the minimum number of semesters, by counting Kahn levels; and the alien dictionary, where edges come from the first differing letter of adjacent words.

How does this apply to running a DAG of jobs on a cluster?Show answer

Kahn's algorithm is the scheduler. Jobs with in-degree 0 are ready; when one finishes, I decrement its children and dispatch any that reach zero. Python's graphlib exposes exactly that as get_ready() and done(). For production I'd add persisted in-degrees so a restart resumes, idempotent jobs so retries are safe, and a cycle check at submit time so a bad DAG fails fast instead of hanging.