Course Schedule
The key idea
Model the courses as a directed graph where an edge
b -> a means b is a prerequisite of a. You can finish every course if and only if this graph has no cycle. A cycle is a circular dependency that can never be satisfied.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] means that you must take course bi first if you want to take course ai.
For example, the pair [0, 1] means that to take course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCourses- All the pairs
prerequisites[i]are distinct.
Examples
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Complexity
Time: O(V + E) Space: O(V + E)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization