Course Schedule II

Solution Code
def findOrderDFS(numCourses: int, prerequisites: list[list[int]]) -> list[int]:
    adj = [[] for _ in range(numCourses)]
    for dest, src in prerequisites:
        adj[src].append(dest)
        
    state = [0] * numCourses # 0: unvisited, 1: visiting, 2: visited
    order = []
    has_cycle = False
    
    def dfs(u):
        nonlocal has_cycle
        if has_cycle: return
        state[u] = 1 # Mark as visiting
        for neighbor in adj[u]:
            if state[neighbor] == 0:
                dfs(neighbor)
            elif state[neighbor] == 1:
                has_cycle = True
                return
        state[u] = 2 # Mark as visited
        order.append(u)
        
    for i in range(numCourses):
        if state[i] == 0:
            dfs(i)
            
    return order[::-1] if not has_cycle else []
Video GuideLeetcode Daily

Time Complexity

O(V + E)

Space Complexity

O(V + E)