Understanding the Problem
The Course Schedule problem involves scheduling a set of courses given a list of prerequisite pairs. Each pair indicates that one course must be completed before another. The challenge is to determine if it's possible to complete all the courses, and if so, in what order.
Representing Courses as a Graph
We treat each course as a node in a directed graph. If course A is a prerequisite for course B, we create a directed edge from A to B. This graph structure helps us track dependencies.
Detecting Cycles Using Topological Sort
To determine a valid order, we use topological sorting, which only works on Directed Acyclic Graphs (DAGs). If a cycle exists (i.e., circular dependency), it’s impossible to complete all courses.
Steps Involved
- Build an adjacency list to represent the graph.
- Track the in-degree (number of prerequisites) for each course.
- Add courses with zero in-degree to a queue—they can be taken immediately.
- Process the queue: for each course, reduce the in-degree of dependent courses. If a dependent course’s in-degree becomes zero, add it to the queue.
Valid Scenarios
If we can process all courses (i.e., the result list has all courses), then a valid order exists and we return it.
Invalid Scenarios
If we cannot process all courses—because a cycle prevents progress—then we return an empty array.
Example
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: Both are valid topological orders satisfying all prerequisites.
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: []
Explanation: A cycle exists (0 → 1 → 0), so no valid order is possible.