Introduction
Course Schedule II is an extension of Course Schedule.
You are given:
numCoursesprerequisites[][]
Goal:
Return a valid order to complete all courses. If it is impossible:
Return [] Example
Input:
numCourses = 4prerequisites = [[1,0], [2,0],[3,1],[3,2]]Output:
[0,1,2,3] Another Valid Output:
[0,2,1,3]Key Observation
Course Schedule I asks:
Can we finish all courses? Course Schedule II asks:
Can we finish all courses?If cycle exists:
No valid ordering exists.Algorithm
1. Build graph
2. Calculate indegree
3. Push indegree 0 nodes
4. Perform BFS
5. Store answer
6. Reduce indegrees7. Return order
Dry Run
Graph:
0 → 1
↓
2
1 → 32 → 3
Indegree:
0 = 0
1 = 1
2 = 13 = 2
Queue:
[0] Process:
0
↓
1,2
↓3
Answer:
[0,1,2,3]
Approach : Topological Sort (Kahn's Algorithm)
Explanation
For every course:
- Build dependency graph.
- Track indegrees.
- Start BFS from indegree 0 nodes.
- Store traversal order.
- Return ordering if all nodes are visited.