Produce a complete course order in which every prerequisite appears before the course that requires it.
Problem
Input. A nonnegative course_count and prerequisite pairs [course, prerequisite] with valid IDs from 0 through course_count - 1.
Output. Return every course exactly once in a valid completion order, or [] if no complete order exists.
Rules. In each pair, the prerequisite must occur earlier than the course.
Include courses absent from the pairs. Repeated pairs do not create additional courses.
Any valid complete order is acceptable. Preserve the inputs; zero courses returns [] as valid success.
Example. Four courses with pairs [[1, 0], [2, 0], [3, 1], [3, 2]] permit [0, 1, 2, 3].
The order [0, 2, 1, 3] is also valid; pairs [[0, 1], [1, 0]] instead require [].
Picture
Reuse zero-indegree elimination. indegree counts unmet incoming edges; ready holds courses with none remaining.
The added state is order: append each course when dequeued, not while its requirements remain unresolved.
For edges 0 -> 1, 0 -> 2, 1 -> 3, and 2 -> 3:
| Event | ready afterward | order |
|---|---|---|
| Seed zero-indegree courses | [0] | [] |
| Emit 0 and remove its edges | [1,2] | [0] |
| Emit 1 and remove its edge | [2] | [0,1] |
| Emit 2 and remove its edge | [3] | [0,1,2] |
| Emit 3 | [] | [0,1,2,3] |
After course one, course three still has one unmet edge. Emitting it then would violate 2 -> 3.
Every emitted prefix respects prerequisites. Return it only when its length equals course_count.
Edges below show remaining requirements; emitted nodes stay visible.
[0,2,1,3] is also valid. FIFO seed order and adjacency insertion order choose one witness, not a canonical order.
Problem trace
Append eligible courses to a saved order; return it only when every course appears
Original dependency matrix
- example
- course_count=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]]
- edge meaning
- matrix cell is prerequisite -> course
- indegree
- [0,1,1,2]
Original dependency matrix
- current
- not shown→0
- ready
- [0]→[]
- order
- []→[0]
Original dependency matrix
- remove edge
- not shown→(1, 2)
- indegree
- [0,1,1,2]→[0,0,1,2]
- ready
- []→[1]
Original dependency matrix
- remove edge
- (1, 2)→(1, 3)
- indegree
- [0,0,1,2]→[0,0,0,2]
- ready
- [1]→[1,2]
Original dependency matrix
- remove edge
- (1, 3)→not shown
- current
- not shown→1
- ready
- [1,2]→[2]
Original dependency matrix
- remove edge
- not shown→(2, 4)
- indegree
- [0,0,0,2]→[0,0,0,1]
- transition
- not shown→2 -> 1; do not enqueue
Original dependency matrix
- remove edge
- (2, 4)→not shown
- current
- not shown→2
- ready
- [2]→[]
Original dependency matrix
- remove edge
- not shown→(3, 4)
- indegree
- [0,0,0,1]→[0,0,0,0]
- ready
- []→[3]
Original dependency matrix
- remove edge
- (3, 4)→not shown
- current
- not shown→3
- ready
- [3]→[]
Original dependency matrix
- check
- not shown→4 == 4
- edge check
- not shown→0<1, 0<2, 1<3, 2<3
- result
- not shown→[0,1,2,3]
- Recognize it
- Directed prerequisites require one valid linear order; a cycle is present when some vertex never reaches zero indegree.
- Keep true
- Every ready vertex has zero incoming edges from un-emitted vertices, and order is a valid topological prefix; each outgoing edge is removed exactly once.
- Reuse it
- Remove resolved requirements one edge at a time and enqueue exactly on transition to zero; retain the emitted prefix when an order, not just feasibility, is required.
Reference drawing
Problem trace
Append eligible courses to a saved order; return it only when every course appears
Execution trace
Original dependency matrix
- example
- course_count=4, prerequisites=[[1,0],[2,0],[3,1],[3,2]]
- edge meaning
- matrix cell is prerequisite -> course
- indegree
- [0,1,1,2]
Original dependency matrix
- current
- not shown→0
- ready
- [0]→[]
- order
- []→[0]
Original dependency matrix
- remove edge
- not shown→(1, 2)
- indegree
- [0,1,1,2]→[0,0,1,2]
- ready
- []→[1]
Original dependency matrix
- remove edge
- (1, 2)→(1, 3)
- indegree
- [0,0,1,2]→[0,0,0,2]
- ready
- [1]→[1,2]
Original dependency matrix
- remove edge
- (1, 3)→not shown
- current
- not shown→1
- ready
- [1,2]→[2]
Original dependency matrix
- remove edge
- not shown→(2, 4)
- indegree
- [0,0,0,2]→[0,0,0,1]
- transition
- not shown→2 -> 1; do not enqueue
Original dependency matrix
- remove edge
- (2, 4)→not shown
- current
- not shown→2
- ready
- [2]→[]
Original dependency matrix
- remove edge
- not shown→(3, 4)
- indegree
- [0,0,0,1]→[0,0,0,0]
- ready
- []→[3]
Original dependency matrix
- remove edge
- (3, 4)→not shown
- current
- not shown→3
- ready
- [3]→[]
Original dependency matrix
- check
- not shown→4 == 4
- edge check
- not shown→0<1, 0<2, 1<3, 2<3
- result
- not shown→[0,1,2,3]
- Recognize it
- Directed prerequisites require one valid linear order; a cycle is present when some vertex never reaches zero indegree.
- Keep true
- Every ready vertex has zero incoming edges from un-emitted vertices, and order is a valid topological prefix; each outgoing edge is removed exactly once.
- Reuse it
- Remove resolved requirements one edge at a time and enqueue exactly on transition to zero; retain the emitted prefix when an order, not just feasibility, is required.
Code
from collections import deque
def find_order(course_count: int, prerequisites: list[list[int]]) -> list[int]:
graph = [[] for _ in range(course_count)]
indegree = [0] * course_count
for course, prerequisite in prerequisites:
graph[prerequisite].append(course)
indegree[course] += 1
ready = deque(course for course in range(course_count) if indegree[course] == 0)
order = []
while ready:
course = ready.popleft()
order.append(course)
for next_course in graph[course]:
indegree[next_course] -= 1
if indegree[next_course] == 0:
ready.append(next_course)
return order if len(order) == course_count else []
For courses and stored edges, work and storage are . A cycle can block other downstream courses too. Queue exhaustion alone does not certify a complete order.
Change Priority or Check the Witness
Start from find_order. Two adjustable parts are ready-course selection and how the returned order is checked.
-
Choose the smallest eligible ID.
New task: Return the lexicographically smallest valid order.
Picture and change: Replace FIFO removal with minimum-heap removal. Keep zero-indegree eligibility and every edge decrement.
Code: Complete replacement:
import heapq def lexicographic_course_order(course_count, prerequisites): graph = [[] for _ in range(course_count)] indegree = [0] * course_count for course, prerequisite in prerequisites: graph[prerequisite].append(course) indegree[course] += 1 ready = [course for course in range(course_count) if indegree[course] == 0] heapq.heapify(ready) order = [] while ready: course = heapq.heappop(ready) order.append(course) for next_course in graph[course]: indegree[next_course] -= 1 if indegree[next_course] == 0: heapq.heappush(ready, next_course) return order if len(order) == course_count else []Check: For
[[2,0],[1,0],[3,1],[3,2]], FIFO emits[0,2,1,3]; the heap emits[0,1,2,3].The smallest ready course can safely lead the remaining valid order. Choosing it repeatedly minimizes the first differing position.
Use when: The output needs this explicit tie policy. Work becomes ; storage remains .
-
Verify a proposed order.
New task: Check a candidate containing hashable integer IDs without regenerating the source’s preferred witness.
Picture and change: Confirm the entire unique course universe, then map each course to its position.
Code: Complete independent verifier under the same prerequisite-ID contract:
def valid_course_order(course_count, prerequisites, order): if len(order) != course_count or set(order) != set(range(course_count)): return False positions = {course: index for index, course in enumerate(order)} return all( positions[prerequisite] < positions[course] for course, prerequisite in prerequisites )Check: The diamond accepts
[0,2,1,3]but rejects[0,1,3,2]because2 -> 3is reversed. With two courses,[0,0]fails completeness even without edges.Use when: Tests or consumers need a certificate, not one particular sequence. Expected work is , with auxiliary storage.
Rebuild Readiness
Does replacing FIFO with a heap change cycle detection?
Answer: No. Both emit only zero-indegree nodes and reject incomplete output. Priority changes witness order and cost, not eligibility.