Back

Course Schedule II

medium

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Test Cases

Copy an input into the main harness and Run to verify
Input
numCourses = 2, prerequisites = [[1,0]]
Expected Output
[0,1]

Explanation: To take course 1 you must first take course 0.

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

Explanation: [0,2,1,3] is also valid.

Input
numCourses = 2, prerequisites = [[1,0],[0,1]]
Expected Output
[]

Explanation: The two courses depend on each other, so no order exists.

Constraints

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

Hints

Hint 1 — click to reveal

This is a topological sort — and an impossible schedule is exactly a cycle in the graph.

Hint 2 — click to reveal

Kahn's algorithm repeatedly takes any course whose prerequisites are all satisfied.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.