Course Schedule II

Medium#210

There are n courses, numbered from 0 to n − 1, and a list of pairs [a, b]: course b has to be taken before course a. Return an order in which all the courses can be taken; any such order will do. If there is none, return an empty list. Our example: 6 courses and the pairs [0, 3], [0, 5], [1, 0], [2, 5], [4, 1], [4, 2]. One answer is [3, 5, 0, 2, 1, 4].

input
numCourses: the number of courses, numbered 0 to numCourses − 1; prerequisites: pairs [a, b], each meaning course b must be taken before course a.
returns
An order to take all the courses in: each course once, and for every pair [a, b] course b before a. If there are several such orders, any of them; if there is none, [].
constraints
  • 1 ≤ numCourses ≤ 500
  • 0 ≤ prerequisites.length ≤ 5000
  • prerequisites[i] = [a, b], 0 ≤ a, b < numCourses
  • a ≠ b
  • the pairs are all different
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
 */
function findOrder(numCourses, prerequisites) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more topological sort problems

Pattern “Topological sort” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.