Understanding the Problem
You're given numCourses
representing total courses labeled from 0
to numCourses - 1
, and an array prerequisites
where each pair [a, b]
means b
must be taken before a
. Your task is to return a possible ordering of courses, such that all prerequisites are met. If there's no way to complete all courses (i.e., there's a cycle), return an empty array.
Graph Representation
We represent this problem as a Directed Graph. Each course is a node, and an edge from course b
to course a
represents the dependency that b
must be taken before a
.
Using Kahn’s Algorithm (BFS-Based Topological Sort)
We create an adjacency list to store which courses depend on others. Alongside, we maintain an indegree
array to count how many prerequisites each course has.
Queue Initialization
We add all courses with zero prerequisites to a queue — they can be taken immediately. Then, we process each course in the queue, and for each dependent course, we reduce its indegree
(one less prerequisite). If a course’s indegree
becomes 0, it gets added to the queue as it's now ready to be taken.
Cycle Detection
If at the end, we’ve added all numCourses
to our result list, we have a valid order. If not, there must be a cycle — making it impossible to finish all courses. In this case, we return an empty array.
Edge Cases
- No prerequisites: All courses can be taken in any order. The result will be any permutation of
[0, 1, ..., numCourses - 1]
.
- Cycle present: Like
[[1, 0], [0, 1]]
. It’s impossible to finish all courses; return []
.
- Multiple independent chains: Like
[[1, 0], [3, 2]]
. Each chain can be taken independently, and order between chains can vary.