![]() |
VOOZH | about |
Given n courses, labeled from 0 to n - 1 and an array prerequisites[] where prerequisites[i] = [x, y] indicates that we need to take course y first if we want to take course x.
Find the ordering of courses we should take to complete all courses. If there are multiple solutions, return any of them. If it is impossible to finish all courses, return an empty array.
Examples:
Input: n = 3, prerequisites[][] = [[1, 0], [2, 1]]
Output: [0, 1, 2]
Explanation: To take course 1, you must finish course 0.
To take course 2, you must finish course 1. So the only valid order is [0, 1, 2].Input: n = 4, prerequisites = [[2, 0], [2, 1], [3, 2]]
Output: [1, 0, 2, 3]
Explanation: Course 2 requires both 0 and 1.
Course 3 requires course 2.
Hence, both [0, 1, 2, 3] and [1, 0, 2, 3] are valid.
Table of Content
We can solve this using Kahn’s Algorithm for Topological Sorting. We can think of each course as a node in a directed graph, and each prerequisite pair [a, b] as a directed edge from b → a.
This means:
Once this graph is built, we have to find an ordering of courses such that every course appears after all its prerequisites this is exactly what topological sorting provides.
0 1 2 3
Time Complexity: O(n+m), where n is the number of courses and m is the size of prerequisite array .
Auxiliary Space: O(n+m)
We can use DFS for topological sorting by treating courses as nodes and prerequisites as edges (b → a). DFS visits all prerequisites before a course, ensuring dependencies come first. By tracking visiting nodes, we can detect cycles. Adding courses to a stack after visiting dependencies and then reversing it gives a valid course order.
1 0 2 3