There are a total of numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course bi
first if you want to take course ai
.
[0, 1]
, indicates that to take course 0
you have to first take course 1
.Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Example 1:
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].
Example 2:
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,1,2,3]. Another correct ordering is [0,2,1,3].
Example 3:
Input: numCourses = 1, prerequisites = [] Output: [0]
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
[ai, bi]
are distinct.This problem asks to find a topological ordering of courses based on prerequisites. A topological ordering is a linear ordering of nodes in a directed acyclic graph (DAG) such that for every directed edge from node A to node B, node A appears before node B in the ordering. If a cycle exists (meaning it's not a DAG), a topological ordering is impossible.
This solution uses Kahn's algorithm, a topological sort algorithm based on breadth-first search (BFS).
Algorithm:
Build the graph: Create an adjacency list (graph) g
representing the course dependencies. g[i]
contains a list of courses that depend on course i
. Also, create an indegree
array where indegree[i]
stores the number of courses that must be taken before course i
.
Find starting nodes: Add all courses with an indegree
of 0 to a queue q
. These courses have no prerequisites and can be taken first.
BFS traversal: While the queue is not empty:
i
from the queue and add it to the ans
array (the result).j
that depends on course i
(neighbors in the graph):
indegree
by 1.indegree[j]
becomes 0, it means all its prerequisites are met, so add it to the queue.Check for cycles: If the length of ans
is equal to numCourses
, it means all courses have been processed, and a topological ordering has been found. Otherwise, a cycle exists, and an empty array is returned.
Time Complexity Analysis:
Space Complexity Analysis:
g
requires O(V + E) space.indegree
array requires O(V) space.q
and the ans
array require O(V) space in the worst case.Code Explanations (Python Example):
from collections import defaultdict, deque
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
g = defaultdict(list) # Adjacency list
indeg = [0] * numCourses # Indegree array
for a, b in prerequisites: #Building the graph and indegree array
g[b].append(a)
indeg[a] += 1
q = deque(i for i, x in enumerate(indeg) if x == 0) #Finding starting nodes
ans = [] # Result array
while q: #BFS Traversal
i = q.popleft()
ans.append(i)
for j in g[i]:
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return ans if len(ans) == numCourses else [] #Checking for Cycles
The other language examples follow the same algorithm with minor syntactic variations. They all efficiently solve the problem using Kahn's algorithm, achieving a linear time complexity.