☰ All problems

64. Course Schedule

MediumGraphDFSBFS

There are numCourses courses, labelled 0 to numCourses - 1. Each entry prerequisites[i] = [a, b] means course b must be completed before course a can be taken.

Return true if there is some order in which every course can be completed, and false otherwise.

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

Explanation: Take course 0, then course 1.

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

Explanation: Each course requires the other first, so neither can ever start.

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

Explanation: One valid order is 0, 1, 2, 3.

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= a, b < numCourses and a != b
  • All pairs are distinct

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