![]() |
VOOZH | about |
You have to complete n courses. There are m requirements of form "course a has to be completed before course b". Your task is to find an order in which you can complete the courses.
Examples:
Input: n = 5, m = 3, requirements[][] = {{1, 2}, {3, 1}, {4, 5}}
Output: 3 4 1 5 2
Explanation:
- Since course 3 and 4 have no requirements, we can complete course 3 and 4.
- After completing course 3, we can complete course 1.
- After completing course 4, we can complete course 5.
- After completing course 1, we can complete course 2.
Input: n = 4, m = 2, requirements[][] = {{4, 2}, {3, 1}}
Output: 3 4 1 2
Explanation:
- Since course 3 and 4 have on requirements, we can complete course 3 and 4.
- After completing course 3, we can complete course 1.
- After completing course 4, we can complete course 2.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Topological Sort. Each course can be considered as a node and each requirement (a, b) can be considered as a directed edge from node a to node b. Now, we can find the topological sort of the graph to find the order in which courses can be completed.
Step-by-step approach:
Below is the implementation of the algorithm:
3 4 1 5 2
Time Complexity: O(N)
Auxiliary Space: O(N)