Course Schedule
1 approach, code in every language
Problem description
You are given an integer numCourses representing the number of courses labeled from 0 to numCourses - 1. You are also given a list prerequisites where each entry [a, b] means you must complete course b before you are allowed to take course a.
Decide whether it is possible to finish every course. Return true if a valid order of study exists, and false otherwise.
The answer is false exactly when the prerequisite relationships form a cycle, because a cycle would force a course to depend on itself either directly or indirectly.
Example 1
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
There are two courses. Course 1 depends on course 0, so the order 0 then 1 finishes everything.
Example 2
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Course 1 needs course 0 and course 0 needs course 1. This circular dependency makes both impossible.
Constraints
1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= a_i, b_i < numCoursesAll the pairs prerequisites[i] are unique.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Apprenticeship Skill Plan is our own problem on the technique behind Course Schedule: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free