CodingNodes / Graphs / Course Schedule System design Space play · ←→ step · R restart

Problem

A school offers numCourses courses, numbered 0 to numCourses - 1. Some courses have a prerequisite: a pair [a, b] in prerequisites means course b must be finished before you can start course a.

You take one course at a time. Return true if it is possible to finish every course, and false if some courses wait for each other in a circle so that at least one can never be started.

Constraints

  • 1 ≤ numCourses ≤ 2000
  • 0 ≤ prerequisites.length ≤ 5000
  • 0 ≤ a, b < numCourses, and every pair appears at most once (a pair may list a course as its own prerequisite)

Examples: pick one to animate

Solutions

TimeO(V + E) SpaceO(V + E)

Time: Building the graph reads every pair once, and every course and every arrow is handled once while courses are taken.

Space: The adjacency lists hold every arrow, and the indegree array and the queue hold at most one entry per course.

A course with no unfinished prerequisites can be taken right now. Count each course's prerequisites (its indegree), start with the courses at 0, and every time you take a course, lower the count of the courses that waited for it. A course whose count reaches 0 joins the queue. If all courses get taken there is no circle. If the queue runs dry first, the courses left over wait for each other.