Schedule Courses Given Prerequisites
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests directed graph modeling, cycle detection, and topological ordering using Kahn's algorithm or DFS.
You are building a course scheduler. There are n courses numbered from 0 to n-1. Some courses have prerequisites: a prerequisite relationship [a, b] means that course b must be completed before you can take course a.
Your task is to determine whether it is possible to complete all courses, and if so, return any valid order in which the courses can be taken that respects all prerequisite relationships.
If no valid ordering exists (because the prerequisites form a cycle), return an empty list.
Input
n: an integer representing the number of coursesprerequisites: a list of prerequisite pairs[a, b]wherebmust be completed beforea
Output
- A list of
nintegers representing a valid course ordering - An empty list
[]if no valid ordering exists
Constraints
1 ≤ n ≤ 100,0000 ≤ len(prerequisites) ≤ 200,000- Each prerequisite pair contains valid course numbers in the range
[0, n-1] - There may be duplicate prerequisite pairs
- A course may appear as a prerequisite for itself (which creates an impossible cycle)
Notes
- Multiple valid orderings may exist; you may return any one of them
- If there are no prerequisites, any permutation of courses
0throughn-1is valid - Disconnected components in the prerequisite graph should be handled correctly
Examples
Example 1
Input: find_course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [0, 1, 2, 3]
Example 2
Input: find_course_order(2, [[1, 0], [0, 1]])
Output: []
Example 3
Input: find_course_order(3, [])
Output: [0, 1, 2]
Hints
Hint 1
Model the problem as a directed graph where each prerequisite pair creates an edge. What property must this graph have for a valid ordering to exist?
Hint 2
Track how many prerequisites each course has. Which courses can be taken immediately? Once you complete a course, how does that affect courses that depend on it?
Hint 3
Kahn's algorithm processes nodes with zero incoming edges iteratively. If you cannot process all n courses, what does that tell you about the graph structure?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding a topological ordering of a directed graph. We model each course as a node and each prerequisite relationship [a, b] as a directed edge from b to a (meaning b must come before a).
A valid course ordering exists if and only if the graph contains no cycles. We use Kahn's algorithm to compute the topological sort:
-
Build the graph: Create an adjacency list where each prerequisite points to the courses that depend on it. Track the in-degree (number of prerequisites) for each course.
-
Find starting points: Identify all courses with zero in-degree (no prerequisites). These can be taken immediately.
-
Process courses iteratively: Remove a course with zero in-degree, add it to the result, and decrease the in-degree of all courses that depend on it. When a dependent course reaches zero in-degree, it becomes ready to process.
-
Detect cycles: If we successfully process all
ncourses, return the ordering. If some courses remain unprocessed, they must be part of a cycle, so return an empty list.
Correctness
Each course is added to the result only after all its prerequisites have been processed, since we wait for its in-degree to reach zero. Courses involved in a cycle never reach zero in-degree because they depend on each other, ensuring cycle detection is correct. The algorithm handles disconnected components naturally since all courses with zero in-degree are initially added to the queue.
Complexity
- Time: O(n + m) where m is the number of prerequisite pairs. Each course is processed once, and each edge is examined once when reducing in-degrees.
- Space: O(n + m) for the adjacency list, in-degree array, and queue.
Implementation
from typing import List
from collections import deque, defaultdict
def find_course_order(n: int, prerequisites: List[List[int]]) -> List[int]:
# Build adjacency list and in-degree count
graph = defaultdict(list)
in_degree = [0] * n
for course, prereq in prerequisites:
graph[prereq].append(course)
in_degree[course] += 1
# Initialize queue with all courses that have no prerequisites
queue = deque([i for i in range(n) if in_degree[i] == 0])
result = []
# Kahn's algorithm for topological sort
while queue:
course = queue.popleft()
result.append(course)
# Reduce in-degree for all dependent courses
for dependent in graph[course]:
in_degree[dependent] -= 1
if in_degree[dependent] == 0:
queue.append(dependent)
# If we couldn't process all courses, there's a cycle
return result if len(result) == n else []