Skip to main content
CodeOath
← All problems

Problem

Course Schedule

Medium
  • graphs
  • topological-sort

Courses are labeled 0 to numCourses - 1. Each pair [course, prereq] in prerequisites says that prereq has to be finished before course can be started.

Return true if the courses can be finished in some order that respects every pair, and false if they cannot. The answer is false exactly when the pairs form a cycle.

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

0, 1, 2, 3, 4 is a valid order, because every course comes after the courses it needs. Course 4 has two prerequisites, which is not a cycle.

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

course 1 needs 0, course 2 needs 1 and course 0 needs 2, so the three wait on each other in a circle and none can start. Course 3 is free, but all four courses have to be finished.

Example 3
Input
numCourses = 3, prerequisites = []
Output
true
Explanation

there are no pairs, so any order works.

Constraints:

  • 0 <= course, prereq < numCourses for every pair
  • prerequisites may be empty

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.