You are given a total of numCourses
courses you have to take, labeled from 0
to numCourses-1
. Some courses may have prerequisites, for example, to take course 0
you have to first take course 1
, which is expressed as a pair: [0, 1]
.
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
If there are multiple valid orderings, return any of them. If it is impossible to finish all courses, return an empty array.
Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,2,1,3].
numCourses
will be a positive integer.prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course bi
before course ai
.To solve this problem, we’ll use Kahn’s Algorithm for Topological Sorting of a Directed Acyclic Graph (DAG). The main steps are:
from collections import deque, defaultdict
def findOrder(numCourses, prerequisites):
# Step 1: Initialize graph & in-degree array
graph = defaultdict(list)
in_degree = [0] * numCourses
# Step 2: Populate graph and in-degree array
for course, pre in prerequisites:
graph[pre].append(course)
in_degree[course] += 1
# Step 3: Find courses with no prerequisites
queue = deque(course for course in range(numCourses) if in_degree[course] == 0)
order = []
# Step 4: Process courses
while queue:
course = queue.popleft()
order.append(course)
for neighbor in graph[course]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
# Step 5: Check for cycles
if len(order) == numCourses:
return order
else:
return []
# Example usage:
print(findOrder(2, [[1, 0]])) # Output: [0, 1]
print(findOrder(4, [[1, 0], [2, 0], [3, 1], [3, 2]])) # Output: [0, 2, 1, 3] (or any valid order)
This solution is efficient for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?