Build an adjacency list and an in-degree array from the prerequisites. For each pair , add edge and increment indegree[a].
Push every course with into a queue. These courses have no prerequisites.
While the queue is not empty, pop a course , add it to the result. For each neighbor of , decrement indegree[v]. If indegree[v] becomes , push into the queue.
After the loop, check the result size. If it equals , return the result. Otherwise, a cycle exists, so return an empty array.
This runs in time and uses space.