Skip to main content

Course Schedule II

Question

None

Example 1
Input: numCourses = 2, prerequisites = [[1,0]] 
Output: [0,1]

Solution

all//Course Schedule II.py


class Solution:
def findOrder(self, numCourses, prerequisites):
in_degree = [[] for _ in range(numCourses)]
out_degree = [0] * numCourses
for x, y in prerequisites:
in_degree[y].append(x)
out_degree[x] += 1
queue = []
for i in range(numCourses):
if out_degree[i] == 0:
queue.append(i)
res = []
while queue:
course = queue.pop(0)
res.append(course)
for x in in_degree[course]:
out_degree[x] -= 1
if out_degree[x] == 0:
queue.append(x)
if len(res) != numCourses:
return []
return res