coding•DSA & Problem Solving•Graphs & Backtracking
Course Schedule II
Problem Statement
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.
### Constraints
- `1 <= numCourses <= 2000`
- `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
- `prerequisites[i].length == 2`
- `0 <= ai, bi < numCourses`
- `ai != bi`
### Input Format
- Line 1: An integer `numCourses`.
- Subsequent lines: Each line contains two space-separated integers `ai bi`.
### Output Format
Print the space-separated course ordering, or an empty line if impossible.
Sample Cases
Example 1Sample Case
Input: 2
1 0
Output: 0 1
Example 2Sample Case
Input: 4
1 0
2 0
3 1
3 2
Output: 0 1 2 3
Example 3Sample Case
Input: 2
0 1
Output: 1 0
Example 4Sample Case
Input: 2
Output: 0 1
Constraints
Runtime Limit: 2000 ms per test batch
Memory Limit: 256 MB
Standard I/O stream reading
Official submissions are evaluated against hidden test cases on the server to verify time & memory complexity.