# 210. Course Schedule II

<https://leetcode.com/problems/course-schedule-ii/>

## solution

```python
import collections

class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        courses = collections.defaultdict(set)
        pres = collections.defaultdict(set)

        for (x, y) in prerequisites:
            courses[y].add(x)  # 上完这个课之后可以上的
            pres[x].add(y)  # 这个课程的所有先修课程

        no_pre = [i for i in range(numCourses) if not pres[i]]

        res = []
        count = 0
        while no_pre:
            take_course = no_pre.pop()
            count += 1
            res.append(take_course)
            for i in courses[take_course]:
                pres[i].remove(take_course)
                if not pres[i]:
                    no_pre.append(i)

        return res if count == numCourses else []
```

时间复杂度：O(V + E)\
空间复杂度：O(V + E)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://longxingtan.gitbook.io/mle-interview/01_leetcode/08_bfs/210.-course-schedule-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
