Course Schedule

35 min · canFinish()

A study plan can fail before the semester begins: Course A needs B, B needs C, and C quietly needs A. No first course exists.

You're given numCourses courses labeled from 0 through numCourses - 1 and a list prerequisites. A pair [course, prerequisite] means you must finish prerequisite before taking course.

Return true if you can finish every course, or false if the requirements contain a cycle — a dependency chain that leads back to its starting course. Each pair is a directed edge, a one-way dependency from the prerequisite to the course. Separate groups of courses are allowed, and a course may require nothing.

Constraints

  • 1 <= numCourses <= 2_000
  • 0 <= prerequisites.length <= 5_000
  • Every pair contains two course labels in the range 0..numCourses - 1.
  • Prerequisite pairs are distinct, and no course is its own prerequisite.

Hints

Name the failure

The schedule is impossible exactly when the directed graph contains a cycle. A DFS can detect an edge back to a course still on the current path.

Find what can start now

Count each course's unmet prerequisites. Any course with a count of zero is ready immediately.

Consume the plan

Take a ready course, reduce the counts of courses that depend on it, and enqueue any count that reaches zero. You succeed only if this process consumes every course.

Follow-up

Can you extend your solution to return one concrete course order when the plan is possible, and return an empty array otherwise?

Visible cases

Examples

Example 1

ready
Input
numCourses = 2
prerequisites = [
  [
    1,
    0
  ]
]
Expected
true
Why
take course 0, then course 1

Example 2

ready
Input
numCourses = 2
prerequisites = [
  [
    1,
    0
  ],
  [
    0,
    1
  ]
]
Expected
false
Why
each course waits for the other

Example 3

ready
Input
numCourses = 1
prerequisites = []
Expected
true
Why
one course with no prerequisite is immediately finishable

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite