Home Leetcode

Course Schedule

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 course 0 you have to first take course 1.

Return true if you can finish all courses. Otherwise, return false.

Constraints:

def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
    def dfs(root: int) -> bool:
        if root not in graph: return True
        if state[root] == 1: return False
        if state[root] == 2: return True

        state[root] = 1
        for course in graph[root]:
            if not dfs(course):
                return False
        
        state[root] = 2
        return True
    
    state = {i: 0 for i in range(numCourses)}
    graph = {}

    for edge in prerequisites:
        course, prereq = edge[0], edge[1]
        if prereq not in graph:
            graph[prereq] = []
        if course not in graph:
            graph[course] = []

        graph[prereq].append(course)
    
    for i in range(numCourses):
        if not dfs(i):
            return False

    return True

Time Complexity

Space Complexity