Return a topological order of courses. prerequisites[i]=[a,b] means take b before a. Return [] if impossible (cycle).
n=2, prereqs=[[1,0]][0,1]In-degree 0 = can take now. After taking a course, decrement inDeg of dependents. New 0s get enqueued. Cycle → some nodes never reach 0 → idx<n.
Generating permutations and checking each one is far too slow. Kahn’s algorithm already produces an order as a side effect.
Run the same in degree process as in Course Schedule. Every time a course leaves the queue, append it to the answer. A course only enters the queue after all its prerequisites have left it. So the answer list is automatically a valid order. If the list is shorter than the number of courses, there was a cycle, so return an empty array.
The order in which Kahn’s queue releases courses is a topological order. A short result means a cycle.
Run the animation above on your own input, or watch the 1:50 video explanation of Course Schedule II with a dry run and Java code.