☰ All problems

Course Schedule

MediumGraphDFSBFS

A university's degree planner checks new curricula for mistakes. A curriculum has numCourses courses numbered from 0 to numCourses - 1, and each pair prerequisites[i] = [a, b] says that course b has to be passed before a student may enrol in course a.

Return true if a student could pass every course in some order that respects all of the prerequisites, and false if the rules make that impossible.

Example 1
Input: numCourses = 5, prerequisites = [[2,0],[2,1],[3,2],[4,2]]
Output: true

Explanation: One valid order is 0, 1, 2, 3, 4: course 2 needs both 0 and 1, and courses 3 and 4 each need 2.

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

Explanation: Course 0 needs 1, course 1 needs 2 and course 2 needs 0, so none of them can be taken first.

Example 3
Input: numCourses = 4, prerequisites = []
Output: true

Explanation: Without prerequisites, the courses can be taken in any order.

Constraints

  • numCourses is between 1 and 2000.
  • There are at most 5000 prerequisite pairs, and no pair appears twice.
  • In every pair [a, b], both courses exist and a is different from b.

Follow-up: Return an actual order in which to take the courses (or an empty array if none exists).

💡 Hint 1

Model courses as nodes and each prerequisite [a, b] as a directed edge b → a. When is it impossible to finish?

💡 Hint 2

All courses can be finished exactly when the graph has no cycle.

💡 Hint 3

Kahn's algorithm: repeatedly take a course with no remaining prerequisites and remove its outgoing edges. If you manage to take all of them, there is no cycle. (A DFS with three node colours works too.)

/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {boolean}
 */
function canFinish(numCourses, prerequisites) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc