Command Palette

Search for a command to run...

Module 24

Topological Sort

Order tasks so every dependency comes first: Kahn's algorithm, DFS finishing order, levels, unique orders, and DP over a DAG.

Intermediate 3 lessons 7 problems ~35 min of lessons

A topological order lists the nodes of a directed graph so that every edge goes from earlier to later: every prerequisite before the course that needs it, every build step before the step that uses its output. It exists exactly when the graph has no cycle (a DAG).

This module teaches the two standard algorithms, Kahn's in-degree queue and reversed DFS finishing order. It then puts them to work: counting semesters (levels), checking whether the order is unique, recovering an unknown alphabet, and computing longest paths and earliest finish times with DP in topological order.

Best after: Cycle Detection, Breadth-First Search

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Produce the order, not just yes or no. Here the smallest available course is always taken, so the answer is unique.

  2. Build the graph yourself from comparisons, then sort it, catching the invalid-prefix case.

  3. Kahn's algorithm level by level: the number of levels is the minimum number of rounds.

  4. DP in topological order: earliest finish = own time + latest prerequisite finish.

  5. A topological order is unique exactly when there is only ever one choice.

  6. Kahn's idea on an undirected tree: peel leaves layer by layer until the centre remains.

  7. A grid with "move to a larger value" edges is a DAG, so memoised DFS (DP over the DAG) gives the longest path.