> ## 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 Python Solution with Tests

> Tested Python solution for LeetCode 207 with 12 pytest cases. Generate a practice environment with lcpy.

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

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

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 207   # by problem number
lcpy gen -s course_schedule   # 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 `true` if you can finish all courses. Otherwise, return `false`.

### Examples

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

**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

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

**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

### Constraints

* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i] are **unique**.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(V + E) where V = num_courses, E = prerequisites
    # Space: O(V + E) for adjacency list and recursion stack
    def can_finish(self, num_courses: int, prerequisites: list[list[int]]) -> bool:
        UNVISITED, VISITING, VISITED = 0, 1, 2  # noqa: N806

        graph: list[list[int]] = [[] for _ in range(num_courses)]
        for course, prereq in prerequisites:
            graph[course].append(prereq)

        state = [UNVISITED] * num_courses

        def has_cycle(course: int) -> bool:
            if state[course] == VISITING:  # Currently visiting - cycle detected
                return True
            if state[course] == VISITED:
                return False

            state[course] = VISITING
            for prereq in graph[course]:
                if has_cycle(prereq):
                    return True
            state[course] = VISITED
            return False

        for course in range(num_courses):
            if state[course] == UNVISITED and has_cycle(course):
                return False
        return True
```

## Complexity

| Time                                               | Space                                           |
| -------------------------------------------------- | ----------------------------------------------- |
| O(V + E) where V = num\_courses, E = prerequisites | O(V + E) for adjacency list and recursion stack |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
