Course Schedule II
mediumThere 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 themain harness and Run to verifynumCourses = 2, prerequisites = [[1,0]][0,1]Explanation: To take course 1 you must first take course 0.
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]][0,1,2,3]Explanation: [0,2,1,3] is also valid.
numCourses = 2, prerequisites = [[1,0],[0,1]][]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.
Powered by OneCompiler. Starter code loads automatically — edit and hit Run.