Topological sort: Course Order
A topological order lists the nodes of a directed graph so that every edge points forward. Think of courses with prerequisites, build steps, or tasks that depend on other tasks.
Kahn's algorithm builds the order in O(nodes + edges):
- Count each node's incoming edges (its "in-degree").
- Put every node with in-degree 0 in a queue. Nothing blocks them.
- Take a node, add it to the order, and lower the in-degree of each node it points to. Any that reach 0 join the queue.
If the order ends shorter than the number of nodes, the rest wait on each other: there is a cycle.
The signal: "in what order", "dependencies", or "can this be finished?"
A common mistake: scanning all nodes for in-degree 0 on every step. That is O(n²).
Exercise: finish course_order. Courses are 0 to n - 1. A pair
(a, b) means course b must come before course a. Return any valid order
of all courses, or [] if there is a cycle. Press Check to run the
tests.