🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →

Basic Topological Sort Questions

Six warm-ups to lock both algorithms — Kahn’s and DFS — into muscle memory. By the end you should be able to write either from scratch and pick the right one for a new problem in seconds.

1. Detect a cycle in a directed graph

Tool: Kahn’s count-check (cleanest) or three-color DFS.

O(V + E) time, O(V + E) space.

2. Find any topological order via Kahn’s

Same code as cycle detection, but return the output list.

O(V + E). Returns the empty list on cycle.

3. DFS-based topological sort

O(V + E). Returns the empty list on cycle.

4. Lexicographically smallest topological order

Swap Kahn’s FIFO queue for a min-heap.

O((V + E) log V). One log factor for the heap.

5. Minimum semesters / parallel rounds

Kahn’s-with-rounds — count BFS layers.

O(V + E). Returns -1 on cycle.

6. Count nodes with no dependents (zero outdegree)

A simple warm-up that builds intuition: a leaf-like node in a DAG.

O(V + E). The “outdegree = 0” nodes are the terminal tasks — the leaves of the dependency tree, things nothing else needs.

Mini-quiz

In Kahn's-with-rounds, why does counting rounds give the minimum number of semesters?
The DFS topo sort uses out.reverse() at the end. Could you also use out.insert(0, u) inside dfs?
If you replace Kahn's queue with a STACK (LIFO) instead of FIFO, what do you get?

Next: the ten practice problems — Course Schedule, Course Schedule II, Alien Dictionary, Minimum Height Trees, and more.