> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Course Schedule II Python Solution with Tests

> Tested Python solution for LeetCode 210 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 210, Medium. Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort. [View on LeetCode](https://leetcode.com/problems/course-schedule-ii/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 210   # by problem number
lcpy gen -s course_schedule_ii   # by problem name
```

## Problem

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 the ordering of courses you should take to finish all courses. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.

### Examples

```
Input: numCourses = 2, prerequisites = [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].
```

```
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
```

```
Input: numCourses = 1, prerequisites = []
Output: [0]
```

### Constraints

* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* `ai != bi`
* All the pairs `[ai, bi]` are **distinct**.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/course_schedule_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/course_schedule_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # TOPOLOGICAL SORT using Kahn's Algorithm (BFS-based)
    # Keywords: DAG, in-degree, adjacency list, cycle detection, dependency resolution
    # Time: O(V + E) where V = num_courses, E = len(prerequisites)
    # Space: O(V + E) for adjacency list and in_degree array
    def find_order(self, num_courses: int, prerequisites: list[list[int]]) -> list[int]:
        """
        Topological Sort: Linear ordering of vertices in DAG where all edges go from left to right.

        Algorithm: Kahn's Algorithm (BFS approach)
        1. Build adjacency list and calculate in-degrees
        2. Start with nodes having 0 in-degree (no dependencies)
        3. Remove nodes and update in-degrees of neighbors
        4. If all nodes processed → valid ordering, else cycle exists

        Keywords: Directed Acyclic Graph (DAG), in-degree, out-degree, dependency graph,
                 prerequisite resolution, cycle detection, BFS traversal
        """
        # Build adjacency list and in-degree count
        graph: list[list[int]] = [[] for _ in range(num_courses)]
        in_degree = [0] * num_courses

        for course, prereq in prerequisites:
            graph[prereq].append(course)
            in_degree[course] += 1

        # Start with courses having no prerequisites
        queue = deque([i for i in range(num_courses) if in_degree[i] == 0])
        result = []

        while queue:
            course = queue.popleft()
            result.append(course)

            # Remove this course and update in-degrees
            for neighbor in graph[course]:
                in_degree[neighbor] -= 1
                if in_degree[neighbor] == 0:
                    queue.append(neighbor)

        # Check if all courses can be taken (no cycle)
        return result if len(result) == num_courses else []
```

## Complexity

| Time                                                    | Space                                            |
| ------------------------------------------------------- | ------------------------------------------------ |
| O(V + E) where V = num\_courses, E = len(prerequisites) | O(V + E) for adjacency list and in\_degree array |

## Tags

[Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
