Course Schedule

Medium Advanced graphs AI round

There are numCourses courses, numbered from 0 to numCourses - 1. Each pair [a, b] in prerequisites says that course b has to be finished before course a can be started.

You take the courses one at a time, and finish each one before starting the next. A course can be started only when every course its pairs put before it has been finished.

Return true if every course can be finished in some order, and false if it cannot.

Example 1

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

Take the courses in the order 0, 1, 2, 3: when each one comes up, the one it waits for has been finished.

Example 2

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

Course 0 waits for 1, which waits for 2, which waits for 0: they wait for each other in a circle, so none of them can ever start.

Example 3

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

Constraints

  • 1 ≤ numCourses ≤ 10⁵
  • 0 ≤ prerequisites.length ≤ 10⁵
  • Every pair has two courses, a and b, with 0 ≤ a, b < numCourses
  • a and b may be the same course, and a pair may appear more than once

Watch the explanation

More Advanced graphs

All Advanced graphs problems