Course Schedule II
Problem Statement
Section titled “Problem Statement”You are given a number of courses labeled from 0 to numCourses - 1 and a list of prerequisite pairs prerequisites where prerequisites[i] = [ai, bi] means you must take course bi before taking course ai. Return the ordering of courses you should take to finish all courses. Return an empty array if impossible.
Examples
Section titled “Examples”| numCourses | prerequisites | Output | Explanation |
|---|---|---|---|
| 2 | [[1,0]] | [0,1] | Take course 0, then course 1 |
| 4 | [[1,0],[2,0],[3,1],[3,2]] | [0,2,1,3] or [0,1,2,3] | Valid topological order (multiple valid orderings exist) |
| 3 | [[1,0],[0,1]] | [] | Circular dependency — impossible |
| 1 | [] | [0] | No prerequisites, single course |
Constraints
Section titled “Constraints”1 <= numCourses <= 20000 <= prerequisites.length <= 5000prerequisites[i].length == 20 <= ai, bi < numCoursesai != bi(no self-loops)- All
(ai, bi)are unique
Real-World Applications
Section titled “Real-World Applications”Complexity Comparison
Section titled “Complexity Comparison”| Approach | Time | Space | Notes |
|---|---|---|---|
| DFS Topological | O(n) | O(n) | First approach |
| BFS Kahn | O(n) | O(n) | Second approach |
Approach 1: DFS Topological
Section titled “Approach 1: DFS Topological” ⏱ Time O(n) 💾 Space O(n)
Solution Code
Section titled “Solution Code”def findOrder(numCourses, prerequisites): """DFS topological sort to get course order.""" graph = [[] for _ in range(numCourses)] for course, prereq in prerequisites: graph[course].append(prereq)
state = [0] * numCourses order = []
def dfs(course): if state[course] == 1: return False if state[course] == 2: return True
state[course] = 1 for prereq in graph[course]: if not dfs(prereq): return False state[course] = 2 order.append(course) return True
for i in range(numCourses): if not dfs(i): return [] return orderclass Solution { // TODO: Implement};class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { int[] state = new int[numCourses]; int[][] graph = new int[numCourses][]; int[] size = new int[numCourses];
for (int[] pre : prerequisites) size[pre[0]]++; for (int i = 0; i < numCourses; i++) graph[i] = new int[size[i]];
size = new int[numCourses]; for (int[] pre : prerequisites) graph[pre[0]][size[pre[0]]++] = pre[1];
int[] order = new int[numCourses]; int[] idx = {numCourses - 1};
for (int i = 0; i < numCourses; i++) { if (!dfs(graph, state, i, order, idx)) return new int[]{}; } return order; }
private boolean dfs(int[][] graph, int[] state, int course, int[] order, int[] idx) { if (state[course] == 1) return false; if (state[course] == 2) return true;
state[course] = 1; for (int prereq : graph[course]) { if (!dfs(graph, state, prereq, order, idx)) return false; } state[course] = 2; order[idx[0]--] = course; return true; }}// Graph solution implementationfunction solve() { // TODO: Implement}impl Solution { // TODO: Implement}
pub struct Solution;package main
// TODO: Implement solutionApproach 2: BFS Kahn
Section titled “Approach 2: BFS Kahn” ⏱ Time O(n) 💾 Space O(n)
Solution Code
Section titled “Solution Code”"""Solution for Course Schedule II"""
def solve(): """Implementation for approach 3 of Course Schedule II""" pass
if __name__ == "__main__": print("Solution ready")#include <bits/stdc++.h>using namespace std;
// Solution for Course Schedule II// Approach 3: Implementation
int main() {{ // Main implementation goes here return 0;}}/** * Solution for Course Schedule II * Approach 3 */public class CourseScheduleIiBfsIterative {{
public static void main(String[] args) {{ // Implementation goes here }}}}/** * Solution for Course Schedule II * Approach 3 */
function solve() {{ // Implementation goes here}}
module.exports = solve;/// Solution for Course Schedule II/// Approach 3
fn main() {{ println!("Solution implementation");}}package main
import "fmt"
// Solution for Course Schedule II// Approach 3
func main() {{ fmt.Println("Solution implementation")}}