MediumDepth-First SearchBreadth-First SearchGraphTopological Sort

1 approach, code in every language

Problem description

There are numCourses courses labeled from 0 to numCourses - 1. You are given a list prerequisites where each entry [a, b] means course b must be completed before course a.

Return any ordering of courses that lets you finish all of them. If more than one valid ordering exists you may return any of them.

If it is impossible to finish every course because of a circular dependency, return an empty array.

Example 1

Input: numCourses = 2, prerequisites = [[1,0]]

Output: [0,1]

Course 1 depends on course 0, so course 0 must come first. The order [0, 1] finishes both.

Example 2

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

Output: [0,1,2,3]

Course 0 unblocks 1 and 2, and both feed into 3. The order [0, 1, 2, 3] respects every prerequisite (other valid orders exist).

Constraints

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= numCourses * (numCourses - 1)
  • prerequisites[i].length == 2
  • 0 <= a_i, b_i < numCourses
  • a_i != b_i
  • All the pairs [a_i, b_i] are distinct.

After the pattern

Now solve one you haven't seen.

Module Build Order is our own problem on the technique behind Course Schedule II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free