Course Schedule

MediumTopological sortGrade AAlso known as LeetCode 207

There are numCourses courses, numbered from 0 to numCourses - 1. You get a list of pairs [a, b], meaning you must take course b before you can take course a.

Return true if it is possible to finish every course, and false if the requirements contain a loop that makes it impossible.

Examples

prerequisites
prerequisites: a directed graph with 2 nodes: 0, 1. Arrows: 0 to 1.01

An arrow from one course to another means take the first course before the second.

Input numCourses = 2, prerequisites = [[1, 0]]
Output true
Take course 0, then course 1.
prerequisites
prerequisites: a directed graph with 2 nodes: 0, 1. Arrows: 0 to 1, 1 to 0.01

An arrow from one course to another means take the first course before the second.

Input numCourses = 2, prerequisites = [[1, 0], [0, 1]]
Output false
Each course needs the other first.
prerequisites
prerequisites: a directed graph with 4 nodes: 0, 1, 2, 3. Arrows: 0 to 1, 0 to 2, 1 to 3, 2 to 3.0123

An arrow from one course to another means take the first course before the second.

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

Constraints

  • 1 <= numCourses <= 2,000
  • 0 <= prerequisites.length <= 5,000
  • Each pair has two different courses, and no pair appears twice.

Stuck? Take one hint at a time

Common mistakes
  • Mixing up the direction of a pair, so the graph is reversed.
  • Forgetting courses that appear in no pair, which have a count of 0 and are always takeable.
  • Stopping as soon as the queue is empty without comparing the number taken with the total.
  • Treating the problem as undirected, so two courses that merely share a prerequisite look like a loop.
Questions an interviewer may ask next
  • Return an order in which the courses can be taken. (The order you took them in.)
  • Return all valid orders, or the lexicographically smallest one.
  • Solve it with depth first search and three states per course.
  • Find the minimum number of semesters if you can take any number of courses per semester.

How often this is reported

Commonly reported across 15 of 25 tracked companies
15/25

Grade A: Reported in several independent candidate sources. This reflects what candidates report, not a guarantee of what any company will ask.