- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/course-schedule-ii
- topics: Graph
Description
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.
- For example, the pair
[0, 1], indicates that to take course0you have to first take course1.
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.
Ideas
We need to sort topologically :
Code
Kahn’s algorithm
class Solution:
def findOrder(self, n: int, prerequisites: List[List[int]]) -> List[int]:
adj = [[] for _ in range(n)]
indegree = [0] * n
ans = []
for pair in prerequisites:
course = pair[0]
prerequisite = pair[1]
adj[prerequisite].append(course)
indegree[course] += 1
queue = deque()
for i in range(n):
if indegree[i] == 0:
queue.append(i)
while queue:
current = queue.popleft()
ans.append(current)
for next_course in adj[current]:
indegree[next_course] -= 1
if indegree[next_course] == 0:
queue.append(next_course)
return ans if len(ans) == n else []