← All patterns
20 / 32
Graphs & Networks

Topological Sort

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

prerequisitesorderingcourse scheduledependenciesbuild orderDAG
Practice

Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.

Ask yourself

  1. Ordering with “must come before” constraints?
  2. Course schedule / build dependencies?
  3. Kahn’s BFS on in-degrees, or DFS post-order.

Classic problem

Course Schedule II (LeetCode 210) — Given n courses and prerequisite pairs, return a valid order to take all courses, or [] if impossible.

Input: numCourses = 6, prerequisites = [["C","A"],["C","B"],["D","B"],["E","C"],["E","D"],["F","D"]]

Output: ["A","B","C","D","E","F"] — one valid topological order (multiple valid orderings exist).

Watch it run

Common pitfalls

Cycle → fewer nodes in order than total (detect it).

Forgetting to build in-degrees first.