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

Problem

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

Return an order in which you can take all the courses, one at a time, so that every course comes after its prerequisites. If some courses wait for each other in a circle, no order exists: return an empty list.

Several orders can be valid. In the examples the order is unique, so the expected output is exact.

Constraints

  • 1 ≤ numCourses ≤ 2000
  • 0 ≤ prerequisites.length ≤ numCourses · (numCourses − 1)
  • 0 ≤ a, b < numCourses, a ≠ b, and every pair appears at most once

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, the queue and the order 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, append it to the order and lower the count of the courses that waited for it. A course whose count reaches 0 joins the queue. If the order ends up with all the courses, it is a valid order. If it is shorter, the missing courses wait for each other and no order exists.