Graph Theory37 sections · 1633 units
Open in Course

Course Schedule II - Algorithm

Kahn's step by step

1.1. Build an adjacency list and an in-degree array from the prerequisites. For each pair [a,b][a, b], add edge bab \to a and increment indegree[a].

2.2. Push every course with indegree=0indegree = 0 into a queue. These courses have no prerequisites.

3.3. While the queue is not empty, pop a course uu, add it to the result. For each neighbor vv of uu, decrement indegree[v]. If indegree[v] becomes 00, push vv into the queue.

4.4. After the loop, check the result size. If it equals nn, return the result. Otherwise, a cycle exists, so return an empty array.

This runs in O(V+E)O(V + E) time and uses O(V+E)O(V + E) space.