Course Schedule II - Problem
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.
For example, the pair [0, 1] indicates that to take course 0 you have to first take course 1.
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.
Input & Output
Example 1 — Basic Prerequisites
$
Input:
numCourses = 2, prerequisites = [[1,0]]
›
Output:
[0,1]
💡 Note:
Course 0 has no prerequisites, so take it first. Course 1 requires course 0, so take it after completing course 0.
Example 2 — Multiple Prerequisites
$
Input:
numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
›
Output:
[0,1,2,3]
💡 Note:
Course 0 first (no prerequisites), then courses 1 and 2 (both depend on 0), finally course 3 (depends on both 1 and 2).
Example 3 — Impossible (Cycle)
$
Input:
numCourses = 2, prerequisites = [[1,0],[0,1]]
›
Output:
[]
💡 Note:
Course 1 requires course 0, but course 0 requires course 1. This creates a cycle, making it impossible to complete all courses.
Constraints
- 1 ≤ numCourses ≤ 2000
- 0 ≤ prerequisites.length ≤ numCourses × (numCourses - 1)
- prerequisites[i].length == 2
- 0 ≤ ai, bi < numCourses
- ai ≠ bi
- All the pairs [ai, bi] are distinct.
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code