Course Schedule II
MediumGraphs
There are num_courses courses labelled 0 to num_courses - 1. Each entry prerequisites[i] = [a, b] means you must finish course b before you can take course a.
Return a list containing every course exactly once, in an order you could take them so that each course comes after all of its prerequisites. If several orders work, return any of them. If no order works (the prerequisites contain a circular dependency), return an empty list [].
Example 1
- Input:
- num_courses = 4, prerequisites = [[1, 0], [2, 0], [3, 1], [3, 2]]
- Output:
- [0, 1, 2, 3]
- Explanation
- Course 0 has no prerequisites, courses 1 and 2 need only 0, and course 3 needs both 1 and 2.
[0, 2, 1, 3]is equally correct; any valid order is accepted.
Example 2
- Input:
- num_courses = 3, prerequisites = [[0, 2]]
- Output:
- [1, 2, 0]
- Explanation
- Only course 0 has a prerequisite (course 2). Courses 1 and 2 can go first in either order, so
[2, 1, 0]or[2, 0, 1]would also be accepted.
Example 3
- Input:
- num_courses = 3, prerequisites = [[1, 0], [0, 1]]
- Output:
- []
- Explanation
- Courses 0 and 1 each need the other first, so no order can include them. Even though course 2 is free, the answer is
[].
Constraints
1 <= num_courses <= 20000 <= prerequisites.length <= num_courses * (num_courses - 1)prerequisites[i].length == 20 <= a, b < num_coursesanda != b- All pairs
prerequisites[i]are distinct