GRAPHS / ALGORITHM BRIEF

Topological sort

A topological sort orders the vertices of a directed acyclic graph (DAG) so that for every edge u -> v, u comes before v.

IntermediatePhase 05 / Topic 4 of 10Mental modelComplexityEdge cases
01

Overview

A topological sort orders the vertices of a directed acyclic graph (DAG) so that for every edge u -> v, u comes before v. It answers 'in what order can I do these tasks when some depend on others?' If the graph has a cycle, no valid order exists, which is how you detect impossible dependency chains.

There are two standard algorithms. Kahn's algorithm (BFS) repeatedly removes nodes with in-degree 0. The DFS approach adds each node to the order after all its descendants finish, then reverses. Both run in O(V + E).

Getting dressed

Socks before shoes, shirt before tie, trousers before belt. Some items have no dependency and can go first. A topological order is any sequence that never puts shoes on before socks.

02

When to use it

  • Prerequisites, dependencies, build order, task scheduling.
  • Detect whether dependencies contain a cycle.
  • DP on a DAG: longest path, number of paths, earliest completion time.
  • Reconstruct an order from pairwise constraints (alien dictionary).
03

Problem patterns it solves

Can all tasks finish (cycle check)

Recognize it when: prerequisites might be circular.

  • 207. Course Schedule
  • 802. Find Eventual Safe States
Produce an order

Recognize it when: return a valid course or build order.

  • 210. Course Schedule II
  • 1203. Sort Items by Groups Respecting Dependencies
  • 2115. Find All Possible Recipes from Given Supplies
Derive order from comparisons

Recognize it when: sorted words in an unknown alphabet.

  • 269. Alien Dictionary
  • 444. Sequence Reconstruction
DP over the order

Recognize it when: longest path, minimum time with parallel tasks.

  • 1136. Parallel Courses
  • 2050. Parallel Courses III
  • 329. Longest Increasing Path in a Matrix
Trim leaves layer by layer

Recognize it when: peel nodes with degree 1 (undirected variant).

  • 310. Minimum Height Trees
04

Where it is used in real software

Build systems

Make, Gradle, Bazel, and TypeScript project references compile modules in topological order of their imports.

Package managers

npm, pip, and apt install dependencies before the packages that need them, and report cycles as errors.

Data pipelines

Apache Airflow and dbt run tasks as a DAG: each task starts once all its upstream tasks succeed.

Spreadsheets

Excel recalculates cells in dependency order and reports circular references.

05

Key terms

DAG
Directed acyclic graph: directed edges and no cycles.
In-degree
Number of incoming edges; in-degree 0 means no unmet dependencies.
Kahn's algorithm
BFS that repeatedly takes in-degree 0 nodes.
Reverse postorder
DFS finishing order, reversed, is a topological order.
06

Kahn's algorithm

  1. 1
    Build the graph and in-degrees

    For prerequisite [a, b] (b before a): edge b -> a and indegree[a]++.

  2. 2
    Queue every in-degree 0 node

    They have no remaining dependencies.

  3. 3
    Pop a node and append it to the order

    It can be done now.

  4. 4
    Decrease neighbors' in-degrees

    When a neighbor reaches 0, all its dependencies are done: enqueue it.

  5. 5
    Check the count

    If the order contains fewer than V nodes, the remaining ones are in a cycle.

07

Course schedule with 4 courses

prerequisites = [[1,0], [2,0], [3,1], [3,2]] (0 before 1 and 2; 1 and 2 before 3)

Step 1 / 5
StepPopIn-degree updatesQueue afterOrder so far
Start-in-degrees: 0:0, 1:1, 2:1, 3:2[0][]
101 -> 0, 2 -> 0[1, 2][0]
213 -> 1[2][0, 1]
323 -> 0[3][0, 1, 2]
43-[][0, 1, 2, 3]

NOWStep: Start | Pop: - | In-degree updates: in-degrees: 0:0, 1:1, 2:1, 3:2 | Queue after: [0] | Order so far: []

All 4 courses were ordered, so there is no cycle. [0, 2, 1, 3] would also be valid: topological orders are usually not unique.

08

Implementation

// 210. Course Schedule II with Kahn's algorithmfunction findOrder(numCourses, prerequisites) {  const graph = Array.from({ length: numCourses }, () => []);  const indegree = new Array(numCourses).fill(0);  for (const [course, pre] of prerequisites) {    graph[pre].push(course);    indegree[course]++;  }   const queue = [];  for (let i = 0; i < numCourses; i++) if (indegree[i] === 0) queue.push(i);   const order = [];  for (let head = 0; head < queue.length; head++) {    const node = queue[head];    order.push(node);    for (const next of graph[node]) {      if (--indegree[next] === 0) queue.push(next);    }  }  return order.length === numCourses ? order : []; // [] means a cycle} // DFS version: reverse postorderfunction topoSortDFS(n, graph) {  const state = new Array(n).fill(0); // 0 new, 1 visiting, 2 done  const order = [];  function visit(u) {    if (state[u] === 1) throw new Error("cycle");    if (state[u] === 2) return;    state[u] = 1;    for (const v of graph[u]) visit(v);    state[u] = 2;    order.push(u); // added after all descendants  }  for (let i = 0; i < n; i++) visit(i);  return order.reverse();}
09

Complexity and performance

TimeO(V + E)

Each node and edge processed once.

SpaceO(V + E)

Graph, in-degrees, and queue.

Cycle detectionfree

Order shorter than V means a cycle.

10

Trade-offs

Kahn vs DFS

Kahn's algorithm is iterative, detects cycles by counting, and naturally processes nodes level by level (useful for parallel scheduling). DFS is shorter when you already have DFS code.

Lexicographically smallest order

Replace Kahn's queue with a min-heap to always pick the smallest available node, at O((V + E) log V).

11

Variants and related techniques

Levels for parallel work

Process Kahn's queue level by level; the number of levels is the minimum number of semesters (Parallel Courses).

Longest path in a DAG

Relax edges in topological order: dist[v] = max(dist[v], dist[u] + w). This is O(V + E), unlike general graphs.

Counting paths

ways[v] += ways[u] in topological order.

12

Common mistakes

  • Reversing edge direction.

    Fix: For [a, b] meaning b must come before a, the edge is b -> a.

  • Returning a partial order when a cycle exists.

    Fix: Check order.length === V.

  • Alien dictionary edge cases.

    Fix: A longer word appearing before its own prefix ("abc" before "ab") is invalid.

13

Interview questions

Why does a topological order exist only for DAGs?

In a cycle, every node depends on another node in the cycle, so none can be placed first. Conversely, every DAG has at least one node with in-degree 0 to start from.

How do you find the minimum number of semesters to finish all courses?

Run Kahn's algorithm level by level; each level is one semester, and the answer is the number of levels if all courses are processed.

14

Practice problems

ProblemDifficultyWhat it trains
207. Course ScheduleMediumCycle detection.
210. Course Schedule IIMediumProduce the order.
2115. Find All Possible Recipes from Given SuppliesMediumKahn with string nodes.
310. Minimum Height TreesMediumLeaf trimming.
2050. Parallel Courses IIIHardDP over topological order.
269. Alien DictionaryHardBuild edges from comparisons.