Deviopath › Python

Course Schedule (Topological Sort)

Hard · Algorithms

A topological order lists tasks so that every task comes after the tasks it depends on. Kahn's algorithm does it: count how many unmet prerequisites each task has, start with the tasks that have zero, and every time you take one, lower the count of the tasks that depend on it. If some tasks never reach zero, there is a cycle and no valid order exists.

Many orders can be valid, so use this rule to make the answer unique: whenever several courses are available, take the alphabetically smallest one. A heapq of available courses does exactly that.

Write course_order(courses, prereqs). courses is a list of unique names. Each pair [course, required] in prereqs means required must be taken before course. Return the full order as a list, or [] if a cycle makes it impossible.

Next: Dijkstra Shortest Distances