Course Schedule

MediumGraphs

There are numCourses courses, numbered 0 to numCourses - 1. Each pair [a, b] in prerequisites means you must finish course b before you can take course a.

Return true if there is an order in which you can finish every course, and false if there is not.

Examples

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

Take course 0, then 1, then 2.

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

Course 0 waits for 1, 1 waits for 2 and 2 waits for 0, so none of them can start.

Constraints

  • 1 ≤ numCourses ≤ 2000
  • 0 ≤ prerequisites.length ≤ 5000
  • 0 ≤ a, b < numCourses
  • No pair appears twice.

Stuck?

Hint 1

Draw each course as a node and each prerequisite as an arrow from b to a. You can finish everything exactly when the arrows never loop back on themselves.

Hint 2

Count each course’s unfinished prerequisites. Take the courses at zero, and each one you take lowers the count of the courses it unlocks (Kahn’s algorithm). If you take all of them, return true.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur