Smallest-First Course Ordering With Cycle Check
Trees & GraphsAuto-graded · 19 test casesLast updated
Produce the lexicographically smallest valid course order from prerequisite pairs, or an empty list if a cycle makes it impossible, using a topological sort with a min-heap.
A school offers course_count courses, numbered 0 through course_count - 1. You are given a list of requirement pairs [c, p], each meaning that course p must be completed before course c can be taken.
Return a complete ordering in which every course appears exactly once and every requirement is respected. If no such ordering exists because the requirements contain a cycle, return an empty list.
Choosing among valid orderings. Several valid orderings may exist, and you must return exactly one: the lexicographically smallest one. Compare two orderings position by position, and the one with the smaller course number at the first differing position wins. Equivalently, whenever several courses could be taken next, pick the one with the smallest number.
Special cases.
- A requirement
[c, c]is a cycle, so the answer is[]. - The same requirement may appear more than once. Duplicates do not change the answer.
- If
course_countis0, return[]. - Courses that appear in no requirement must still be included in the ordering.
Constraints
0 <= course_count <= 10^50 <= len(requirements) <= 2 * 10^5- Each requirement is a pair
[c, p]with0 <= c, p < course_count. - The function returns a list of integers: the ordering, or
[]if it is impossible.
Examples
Example 1
Input: plan_course_order(2, [[1, 0]])
Output: [0, 1]
Example 2
Input: plan_course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [0, 1, 2, 3]
Example 3
Input: plan_course_order(2, [[1, 0], [0, 1]])
Output: []
Hints
Hint 1
Treat each requirement as a directed edge from the prerequisite to the course that depends on it, and track how many unmet prerequisites each course has.
Hint 2
A course can be taken when its count of unmet prerequisites reaches zero. Repeatedly take such courses and update the courses that depend on them.
Hint 3
To get the lexicographically smallest order, keep the currently available courses in a min-heap instead of a plain queue. If you finish with fewer than course_count courses, a cycle exists.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the requirements as a directed graph with an edge p -> c for every pair [c, p]. A valid ordering is a topological order of this graph, and one exists exactly when the graph has no cycle.
We use Kahn's algorithm, with a min-heap in place of the usual queue:
- Count, for each course, how many requirement edges point into it (its unmet prerequisites). Duplicate pairs are counted each time, and they are also decremented each time, so they stay consistent.
- Put every course with zero unmet prerequisites into a min-heap.
- Repeatedly pop the smallest course, append it to the answer, and decrement the counter of each course that depends on it. Any course whose counter reaches zero is pushed onto the heap.
- If the answer contains all
course_countcourses, return it. Otherwise a cycle blocked some courses, so return[].
Why it is correct
- Valid order: a course enters the heap only after all its prerequisites have been output, so every requirement is respected.
- Cycle detection: a course on a cycle always has at least one unmet prerequisite that is also on the cycle and never gets output, so its counter never reaches zero. The answer is then shorter than
course_count. A self-loop is the smallest case of this. - Lexicographically smallest: at each step the heap holds exactly the courses that can legally come next. Taking the smallest of them is the best choice for the current position. It never harms later positions, because it only unlocks more options and every other available course stays available.
Complexity
- Time: O((n + m) log n) for
ncourses andmrequirements. Each course is pushed and popped once, and each edge is processed once. - Space: O(n + m) for the adjacency lists, counters and heap.
Reference solution
import heapq
from typing import List
def plan_course_order(course_count: int, requirements: List[List[int]]) -> List[int]:
dependents = [[] for _ in range(course_count)]
unmet = [0] * course_count
for course, prereq in requirements:
dependents[prereq].append(course)
unmet[course] += 1
ready = [c for c in range(course_count) if unmet[c] == 0]
heapq.heapify(ready)
order = []
while ready:
current = heapq.heappop(ready)
order.append(current)
for nxt in dependents[current]:
unmet[nxt] -= 1
if unmet[nxt] == 0:
heapq.heappush(ready, nxt)
return order if len(order) == course_count else []