Course Schedule

Medium#207

There are n courses, numbered from 0 to n − 1, and a list of pairs [a, b]: course b has to be taken before course a. Find out whether all the courses can be taken. Our example: 6 courses and the pairs [1, 0], [2, 1], [3, 2], [1, 3], [4, 0], [5, 4], [5, 3]. The answer is false: courses 1, 2 and 3 each wait for another one of them.

input
numCourses: the number of courses, numbered 0 to numCourses − 1; prerequisites: pairs [a, b], each meaning course b must be taken before course a. A course may need itself.
returns
true if all the courses can be taken in some order that keeps every pair, false if not.
constraints
  • 1 ≤ numCourses ≤ 500
  • 0 ≤ prerequisites.length ≤ 5000
  • prerequisites[i] = [a, b], 0 ≤ a, b < numCourses
  • the pairs are all different
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {boolean}
 */
function canFinish(numCourses, prerequisites) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more topological sort problems

Pattern “Topological sort” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.