#210
Course Schedule II
medium· Graphsruns: 0There are numCourses courses labeled 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [a, b] indicates that you must take course b before course a. Return the order of courses you should take to finish all of them. If there are multiple valid answers, return any. If it is impossible to finish all courses, return an empty array.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 846
class Solution:
def findOrder(
self, numCourses: int, prerequisites: list[list[int]]
) -> list[int]:
graph = {i: [] for i in range(numCourses)}
for course, pre in prerequisites:
graph[course].append(pre)
visit = set()
cycle = set()
order = []
def dfs(course: int) -> bool:
if course in cycle:
return False
if course in visit:
return True
cycle.add(course)
for pre in graph[course]:
if not dfs(pre):
return False
cycle.remove(course)
visit.add(course)
order.append(course)
return True
for course in range(numCourses):
if not dfs(course):
return []
return order
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.